<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>Netty | Skyung-Blog</title>
  <meta name="description" content="基于黑马程序员https:&#x2F;&#x2F;www.bilibili.com&#x2F;video&#x2F;BV1py4y1E7oA?p&#x3D;53&amp;share_source&#x3D;copy_web 入门1. 概述1.1 Netty 是什么？12Netty is an asynchronous event-driven network application frameworkfor rapid development of mai">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty">
<meta property="og:url" content="https://skyung.gitee.io/Skyung/2022/04/20/netty/index.html">
<meta property="og:site_name" content="Skyung-Blog">
<meta property="og:description" content="基于黑马程序员https:&#x2F;&#x2F;www.bilibili.com&#x2F;video&#x2F;BV1py4y1E7oA?p&#x3D;53&amp;share_source&#x3D;copy_web 入门1. 概述1.1 Netty 是什么？12Netty is an asynchronous event-driven network application frameworkfor rapid development of mai">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0006.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0007.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0040.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0042.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0041.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0048.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0047.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0008.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0009.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0010.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0011.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0012.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0049.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0051.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0013.png">
<meta property="og:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0032.png">
<meta property="article:published_time" content="2022-04-19T16:00:00.000Z">
<meta property="article:modified_time" content="2022-05-07T16:00:00.000Z">
<meta property="article:author" content="Skyung">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0006.png">
  <!-- Canonical links -->
  <link rel="canonical" href="https://skyung.gitee.io/Skyung/2022/04/20/netty/index.html">
  
    <link rel="alternate" href="/atom.xml" title="Skyung-Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="images/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/Skyung/css/style.css">

  
  
  
  
<meta name="generator" content="Hexo 5.4.1"></head>


<body class="main-center" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://github.com/cofess" target="_blank">
          <img class="img-circle img-rotate" src="/Skyung/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">Skyung</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">Web Developer</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> Wuhan, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav ">
        
        
        <li class="menu-item menu-item-home">
          <a href="/Skyung/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/Skyung/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/Skyung/categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/Skyung/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-repository">
          <a href="/Skyung/repository">
            
            <i class="icon icon-project"></i>
            
            <span class="menu-title">项目</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-books">
          <a href="/Skyung/books">
            
            <i class="icon icon-book-fill"></i>
            
            <span class="menu-title">书单</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/Skyung/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/Skyung/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="/Skyung/null" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/Skyung/null" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="/Skyung/null" target="_blank" title="Twitter" data-toggle=tooltip data-placement=top><i class="icon icon-twitter"></i></a></li>
        
        <li><a href="/Skyung/null" target="_blank" title="Behance" data-toggle=tooltip data-placement=top><i class="icon icon-behance"></i></a></li>
        
        <li><a href="/Skyung/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎交流与分享经验!</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title">分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/Skyung/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a><span class="category-list-count">20</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签</h3>
    <div class="widget-body">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/Skyung/tags/java/" rel="tag">java</a><span class="tag-list-count">19</span></li><li class="tag-list-item"><a class="tag-list-link" href="/Skyung/tags/jvm/" rel="tag">jvm</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/Skyung/tags/linux/" rel="tag">linux</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/Skyung/tags/redis/" rel="tag">redis</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/Skyung/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag">多线程</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/Skyung/tags/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" rel="tag">并发编程</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/Skyung/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag">设计模式</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/Skyung/tags/%E9%9B%B6%E6%95%A3%E7%82%B9/" rel="tag">零散点</a><span class="tag-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/Skyung/tags/java/" style="font-size: 14px;">java</a> <a href="/Skyung/tags/jvm/" style="font-size: 13px;">jvm</a> <a href="/Skyung/tags/linux/" style="font-size: 13px;">linux</a> <a href="/Skyung/tags/redis/" style="font-size: 13px;">redis</a> <a href="/Skyung/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" style="font-size: 13px;">多线程</a> <a href="/Skyung/tags/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" style="font-size: 13.33px;">并发编程</a> <a href="/Skyung/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" style="font-size: 13.67px;">设计模式</a> <a href="/Skyung/tags/%E9%9B%B6%E6%95%A3%E7%82%B9/" style="font-size: 13px;">零散点</a>
    </div>
  </div>

    
      
  <div class="widget">
    <h3 class="widget-title">归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/Skyung/archives/2022/05/">五月 2022</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/Skyung/archives/2022/04/">四月 2022</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/Skyung/archives/2022/03/">三月 2022</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/Skyung/archives/2022/02/">二月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/Skyung/archives/2021/09/">九月 2021</a><span class="archive-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/Skyung/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
              </p>
              <p class="item-title">
                <a href="/Skyung/2022/05/08/Spring/" class="title">spring</a>
              </p>
              <p class="item-date">
                <time datetime="2022-05-07T16:00:00.000Z" itemprop="datePublished">2022-05-08</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/Skyung/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
              </p>
              <p class="item-title">
                <a href="/Skyung/2022/05/08/netty-RPC/" class="title">Netty-RPC</a>
              </p>
              <p class="item-date">
                <time datetime="2022-05-07T16:00:00.000Z" itemprop="datePublished">2022-05-08</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/Skyung/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
              </p>
              <p class="item-title">
                <a href="/Skyung/2022/05/07/%E5%B8%B8%E7%94%A8%E7%B1%BB%E5%BA%93%E5%92%8CAPI/" class="title">常见类库</a>
              </p>
              <p class="item-date">
                <time datetime="2022-05-06T16:00:00.000Z" itemprop="datePublished">2022-05-07</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/Skyung/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
              </p>
              <p class="item-title">
                <a href="/Skyung/2022/05/07/%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95/" class="title">单元测试</a>
              </p>
              <p class="item-date">
                <time datetime="2022-05-06T16:00:00.000Z" itemprop="datePublished">2022-05-07</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/Skyung/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
              </p>
              <p class="item-title">
                <a href="/Skyung/2022/05/01/netty%E8%81%8A%E5%A4%A9%E5%AE%A4/" class="title">Netty聊天室</a>
              </p>
              <p class="item-date">
                <time datetime="2022-04-30T16:00:00.000Z" itemprop="datePublished">2022-05-01</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
  <aside class="sidebar sidebar-toc collapse   in  " id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <nav id="toc" class="article-toc">
      <h3 class="toc-title">文章目录</h3>
      <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%A5%E9%97%A8"><span class="toc-number">1.</span> <span class="toc-text">入门</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E6%A6%82%E8%BF%B0"><span class="toc-number">1.1.</span> <span class="toc-text">1. 概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-Netty-%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-number">1.1.1.</span> <span class="toc-text">1.1 Netty 是什么？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-Netty-%E7%9A%84%E5%9C%B0%E4%BD%8D"><span class="toc-number">1.1.2.</span> <span class="toc-text">1.2 Netty 的地位</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-4-Netty-%E7%9A%84%E4%BC%98%E5%8A%BF"><span class="toc-number">1.1.3.</span> <span class="toc-text">1.4 Netty 的优势</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-Hello-World"><span class="toc-number">1.2.</span> <span class="toc-text">2. Hello World</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E7%9B%AE%E6%A0%87"><span class="toc-number">1.2.1.</span> <span class="toc-text">2.1 目标</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%AB%AF"><span class="toc-number">1.2.2.</span> <span class="toc-text">2.2 服务器端</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E5%AE%A2%E6%88%B7%E7%AB%AF"><span class="toc-number">1.2.3.</span> <span class="toc-text">2.3 客户端</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-%E6%B5%81%E7%A8%8B%E6%A2%B3%E7%90%86"><span class="toc-number">1.2.4.</span> <span class="toc-text">2.4 流程梳理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%90%86%E8%A7%A3"><span class="toc-number">1.2.4.1.</span> <span class="toc-text">理解</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E7%BB%84%E4%BB%B6"><span class="toc-number">1.3.</span> <span class="toc-text">3. 组件</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-EventLoop"><span class="toc-number">1.3.1.</span> <span class="toc-text">3.1 EventLoop</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#NioEventLoop-%E5%A4%84%E7%90%86%E6%99%AE%E9%80%9A%E4%BB%BB%E5%8A%A1"><span class="toc-number">1.3.1.1.</span> <span class="toc-text">NioEventLoop 处理普通任务</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#NioEventLoop-%E5%A4%84%E7%90%86%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1"><span class="toc-number">1.3.1.2.</span> <span class="toc-text">NioEventLoop 处理定时任务</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#NioEventLoop-%E5%A4%84%E7%90%86-io-%E4%BA%8B%E4%BB%B6"><span class="toc-number">1.3.1.3.</span> <span class="toc-text">NioEventLoop 处理 io 事件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#handler-%E6%89%A7%E8%A1%8C%E4%B8%AD%E5%A6%82%E4%BD%95%E6%8D%A2%E4%BA%BA%EF%BC%9F"><span class="toc-number">1.3.1.4.</span> <span class="toc-text">handler 执行中如何换人？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-Channel"><span class="toc-number">1.3.2.</span> <span class="toc-text">3.2 Channel</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#ChannelFuture"><span class="toc-number">1.3.2.1.</span> <span class="toc-text">ChannelFuture</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CloseFuture"><span class="toc-number">1.3.2.2.</span> <span class="toc-text">CloseFuture</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BC%98%E9%9B%85%E5%85%B3%E9%97%AD"><span class="toc-number">1.3.2.2.1.</span> <span class="toc-text">优雅关闭</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E6%8F%90%E5%8D%87%E7%9A%84%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">1.3.2.3.</span> <span class="toc-text">异步提升的是什么</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-Future-amp-Promise"><span class="toc-number">1.3.3.</span> <span class="toc-text">3.3 Future &amp; Promise</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BE%8B"><span class="toc-number">1.3.3.1.</span> <span class="toc-text">例</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-4-Handler-amp-Pipeline"><span class="toc-number">1.3.4.</span> <span class="toc-text">3.4 Handler &amp; Pipeline</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-5-ByteBuf"><span class="toc-number">1.3.5.</span> <span class="toc-text">3.5 ByteBuf</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%EF%BC%89%E5%88%9B%E5%BB%BA"><span class="toc-number">1.3.5.1.</span> <span class="toc-text">1）创建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%EF%BC%89%E7%9B%B4%E6%8E%A5%E5%86%85%E5%AD%98-vs-%E5%A0%86%E5%86%85%E5%AD%98"><span class="toc-number">1.3.5.2.</span> <span class="toc-text">2）直接内存 vs 堆内存</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%EF%BC%89%E6%B1%A0%E5%8C%96-vs-%E9%9D%9E%E6%B1%A0%E5%8C%96"><span class="toc-number">1.3.5.3.</span> <span class="toc-text">3）池化 vs 非池化</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4%EF%BC%89%E7%BB%84%E6%88%90"><span class="toc-number">1.3.5.4.</span> <span class="toc-text">4）组成</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5%EF%BC%89%E5%86%99%E5%85%A5"><span class="toc-number">1.3.5.5.</span> <span class="toc-text">5）写入</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6%EF%BC%89%E6%89%A9%E5%AE%B9"><span class="toc-number">1.3.5.6.</span> <span class="toc-text">6）扩容</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#7%EF%BC%89%E8%AF%BB%E5%8F%96"><span class="toc-number">1.3.5.7.</span> <span class="toc-text">7）读取</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#8%EF%BC%89retain-amp-release"><span class="toc-number">1.3.5.8.</span> <span class="toc-text">8）retain &amp; release</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#9%EF%BC%89slice"><span class="toc-number">1.3.5.9.</span> <span class="toc-text">9）slice</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#10%EF%BC%89duplicate"><span class="toc-number">1.3.5.10.</span> <span class="toc-text">10）duplicate</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#11%EF%BC%89copy"><span class="toc-number">1.3.5.11.</span> <span class="toc-text">11）copy</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#12%EF%BC%89CompositeByteBuf"><span class="toc-number">1.3.5.12.</span> <span class="toc-text">12）CompositeByteBuf</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#13%EF%BC%89Unpooled"><span class="toc-number">1.3.5.13.</span> <span class="toc-text">13）Unpooled</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ByteBuf-%E4%BC%98%E5%8A%BF"><span class="toc-number">1.3.5.14.</span> <span class="toc-text">ByteBuf 优势</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E5%8F%8C%E5%90%91%E9%80%9A%E4%BF%A1"><span class="toc-number">1.4.</span> <span class="toc-text">4. 双向通信</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%BB%E5%92%8C%E5%86%99%E7%9A%84%E8%AF%AF%E8%A7%A3"><span class="toc-number">1.4.1.</span> <span class="toc-text">读和写的误解</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%BF%9B%E9%98%B6"><span class="toc-number">2.</span> <span class="toc-text">进阶</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E7%B2%98%E5%8C%85%E4%B8%8E%E5%8D%8A%E5%8C%85"><span class="toc-number">2.1.</span> <span class="toc-text">1. 粘包与半包</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E7%B2%98%E5%8C%85%E7%8E%B0%E8%B1%A1"><span class="toc-number">2.1.1.</span> <span class="toc-text">1.1 粘包现象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-%E5%8D%8A%E5%8C%85%E7%8E%B0%E8%B1%A1"><span class="toc-number">2.1.2.</span> <span class="toc-text">1.2 半包现象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-%E7%8E%B0%E8%B1%A1%E5%88%86%E6%9E%90"><span class="toc-number">2.1.3.</span> <span class="toc-text">1.3 现象分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-4-%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-number">2.1.4.</span> <span class="toc-text">1.4 解决方案</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%951%EF%BC%8C%E7%9F%AD%E9%93%BE%E6%8E%A5"><span class="toc-number">2.1.4.1.</span> <span class="toc-text">方法1，短链接</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%952%EF%BC%8C%E5%9B%BA%E5%AE%9A%E9%95%BF%E5%BA%A6"><span class="toc-number">2.1.4.2.</span> <span class="toc-text">方法2，固定长度</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%953%EF%BC%8C%E5%9B%BA%E5%AE%9A%E5%88%86%E9%9A%94%E7%AC%A6"><span class="toc-number">2.1.4.3.</span> <span class="toc-text">方法3，固定分隔符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%954%EF%BC%8C%E9%A2%84%E8%AE%BE%E9%95%BF%E5%BA%A6"><span class="toc-number">2.1.4.4.</span> <span class="toc-text">方法4，预设长度</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E5%8D%8F%E8%AE%AE%E8%AE%BE%E8%AE%A1%E4%B8%8E%E8%A7%A3%E6%9E%90"><span class="toc-number">2.2.</span> <span class="toc-text">2. 协议设计与解析</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-redis-%E5%8D%8F%E8%AE%AE%E4%B8%BE%E4%BE%8B"><span class="toc-number">2.2.1.</span> <span class="toc-text">2.1 redis 协议举例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-http-%E5%8D%8F%E8%AE%AE%E4%B8%BE%E4%BE%8B"><span class="toc-number">2.2.2.</span> <span class="toc-text">2.2 http 协议举例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8D%8F%E8%AE%AE%E8%A6%81%E7%B4%A0"><span class="toc-number">2.2.3.</span> <span class="toc-text">2.3 自定义协议要素</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BC%96%E8%A7%A3%E7%A0%81%E5%99%A8"><span class="toc-number">2.2.3.1.</span> <span class="toc-text">编解码器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%97%B6%E5%80%99%E5%8F%AF%E4%BB%A5%E5%8A%A0-Sharable"><span class="toc-number">2.2.3.2.</span> <span class="toc-text">什么时候可以加 @Sharable</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BC%98%E5%8C%96"><span class="toc-number">3.</span> <span class="toc-text">优化</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-1-%E6%89%A9%E5%B1%95%E5%BA%8F%E5%88%97%E5%8C%96%E7%AE%97%E6%B3%95"><span class="toc-number">3.1.</span> <span class="toc-text">1.1 扩展序列化算法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-2-%E5%8F%82%E6%95%B0%E8%B0%83%E4%BC%98"><span class="toc-number">3.2.</span> <span class="toc-text">1.2 参数调优</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%EF%BC%89CONNECT-TIMEOUT-MILLIS"><span class="toc-number">3.2.0.1.</span> <span class="toc-text">1）CONNECT_TIMEOUT_MILLIS</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%EF%BC%89SO-BACKLOG"><span class="toc-number">3.2.0.2.</span> <span class="toc-text">2）SO_BACKLOG</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%EF%BC%89ulimit-n"><span class="toc-number">3.2.0.3.</span> <span class="toc-text">3）ulimit -n</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4%EF%BC%89TCP-NODELAY"><span class="toc-number">3.2.0.4.</span> <span class="toc-text">4）TCP_NODELAY</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5%EF%BC%89SO-SNDBUF-amp-SO-RCVBUF"><span class="toc-number">3.2.0.5.</span> <span class="toc-text">5）SO_SNDBUF &amp; SO_RCVBUF</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6%EF%BC%89ALLOCATOR"><span class="toc-number">3.2.0.6.</span> <span class="toc-text">6）ALLOCATOR</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#7%EF%BC%89RCVBUF-ALLOCATOR"><span class="toc-number">3.2.0.7.</span> <span class="toc-text">7）RCVBUF_ALLOCATOR</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90"><span class="toc-number">4.</span> <span class="toc-text">源码分析</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%AF%E5%8A%A8%E5%89%96%E6%9E%90"><span class="toc-number">4.0.1.</span> <span class="toc-text">启动剖析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#NioEventLoop-%E5%89%96%E6%9E%90"><span class="toc-number">4.0.2.</span> <span class="toc-text">NioEventLoop 剖析</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#NioEventLoop%E7%9A%84%E7%BB%84%E6%88%90"><span class="toc-number">4.0.2.1.</span> <span class="toc-text">NioEventLoop的组成</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#selector%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="toc-number">4.0.2.2.</span> <span class="toc-text">selector的创建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#NioEventLoop-%E7%9A%84nio%E7%BA%BF%E7%A8%8B"><span class="toc-number">4.0.2.3.</span> <span class="toc-text">NioEventLoop 的nio线程</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#accept-%E5%89%96%E6%9E%90"><span class="toc-number">4.0.3.</span> <span class="toc-text">accept 剖析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#read-%E5%89%96%E6%9E%90"><span class="toc-number">4.0.4.</span> <span class="toc-text">read 剖析</span></a></li></ol></li></ol></li></ol>
    </nav>
  </div>
</aside>

<main class="main" role="main">
  <div class="content">
  <article id="post-netty" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      Netty
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/Skyung/2022/04/20/netty/" class="article-date">
	  <time datetime="2022-04-19T16:00:00.000Z" itemprop="datePublished">2022-04-20</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/Skyung/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/Skyung/tags/java/" rel="tag">java</a>
  </span>


        

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/Skyung/2022/04/20/netty/#comments" class="article-comment-link">评论</a></span>
        
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <p>基于黑马程序员<a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1py4y1E7oA?p=53&amp;share_source=copy_web">https://www.bilibili.com/video/BV1py4y1E7oA?p=53&amp;share_source=copy_web</a></p>
<h1 id="入门"><a href="#入门" class="headerlink" title="入门"></a>入门</h1><h2 id="1-概述"><a href="#1-概述" class="headerlink" title="1. 概述"></a>1. 概述</h2><h3 id="1-1-Netty-是什么？"><a href="#1-1-Netty-是什么？" class="headerlink" title="1.1 Netty 是什么？"></a>1.1 Netty 是什么？</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Netty is an asynchronous event-driven network application framework</span><br><span class="line">for rapid development of maintainable high performance protocol servers &amp; clients.</span><br></pre></td></tr></table></figure>

<p>Netty 是一个异步的、基于事件驱动的网络应用框架，用于快速开发可维护、高性能的网络服务器和客户端</p>
<h3 id="1-2-Netty-的地位"><a href="#1-2-Netty-的地位" class="headerlink" title="1.2 Netty 的地位"></a>1.2 Netty 的地位</h3><p>Netty 在 Java 网络应用框架中的地位就好比：Spring 框架在 JavaEE 开发中的地位</p>
<p>以下的框架都使用了 Netty，因为它们有网络通信需求！</p>
<ul>
<li>Cassandra - nosql 数据库</li>
<li>Spark - 大数据分布式计算框架</li>
<li>Hadoop - 大数据分布式存储框架</li>
<li>RocketMQ - ali 开源的消息队列</li>
<li>ElasticSearch - 搜索引擎</li>
<li>gRPC - rpc 框架</li>
<li>Dubbo - rpc 框架</li>
<li>Spring 5.x - flux api 完全抛弃了 tomcat ，使用 netty 作为服务器端</li>
<li>Zookeeper - 分布式协调框架</li>
</ul>
<h3 id="1-4-Netty-的优势"><a href="#1-4-Netty-的优势" class="headerlink" title="1.4 Netty 的优势"></a>1.4 Netty 的优势</h3><ul>
<li>Netty vs NIO，工作量大，bug 多<ul>
<li>需要自己构建协议</li>
<li>解决 TCP 传输问题，如粘包、半包</li>
<li>epoll 空轮询导致 CPU 100%</li>
<li>对 API 进行增强，使之更易用，如 FastThreadLocal =&gt; ThreadLocal，ByteBuf =&gt; ByteBuffer</li>
</ul>
</li>
<li>Netty vs 其它网络应用框架<ul>
<li>Mina 由 apache 维护，将来 3.x 版本可能会有较大重构，破坏 API 向下兼容性，Netty 的开发迭代更迅速</li>
<li>久经考验，16年，Netty 版本<ul>
<li>2.x 2004</li>
<li>3.x 2008</li>
<li>4.x 2013</li>
<li>5.x 已废弃（没有明显的性能提升，维护成本高）</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="2-Hello-World"><a href="#2-Hello-World" class="headerlink" title="2. Hello World"></a>2. Hello World</h2><h3 id="2-1-目标"><a href="#2-1-目标" class="headerlink" title="2.1 目标"></a>2.1 目标</h3><p>开发一个简单的服务器端和客户端</p>
<ul>
<li>客户端向服务器端发送 hello, world</li>
<li>服务器仅接收，不返回</li>
</ul>
<p>加入依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.netty<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>netty-all<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.1.39.Final<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="2-2-服务器端"><a href="#2-2-服务器端" class="headerlink" title="2.2 服务器端"></a>2.2 服务器端</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//启动器，负责组装netty组件，启动服务器</span></span><br><span class="line"><span class="keyword">new</span> <span class="title class_">ServerBootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>()) <span class="comment">// 1</span></span><br><span class="line">    .channel(NioServerSocketChannel.class) <span class="comment">// 2</span></span><br><span class="line">    .childHandler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;NioSocketChannel&gt;() &#123; <span class="comment">// 3</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(NioSocketChannel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">StringDecoder</span>()); <span class="comment">// 5</span></span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">SimpleChannelInboundHandler</span>&lt;String&gt;() &#123; <span class="comment">// 6</span></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">channelRead0</span><span class="params">(ChannelHandlerContext ctx, String msg)</span> &#123;</span><br><span class="line">                    System.out.println(msg);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    .bind(<span class="number">8080</span>); <span class="comment">// 4</span></span><br></pre></td></tr></table></figure>

<p>代码解读</p>
<ul>
<li><p>1 处，创建 NioEventLoopGroup，也就是boss和worker(线程池 + Selector)</p>
</li>
<li><p>2 处，选择服务器的 ServerSocketChannel实现类，其中 NioServerSocketChannel 表示基于 NIO 的服务器端实现，其它实现还有</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0006.png"></p>
</li>
<li><p>3 处， childHandler也就是决定了woker角色要执行的逻辑。ChannelInitializer初始化器（仅执行一次），它的作用是待客户端 SocketChannel 建立连接后，执行 initChannel 方法以便添加更多的handler</p>
</li>
<li><p>4 处，ServerSocketChannel 绑定的监听端口</p>
</li>
<li><p>5 处，handler，解码 ByteBuf =&gt; String</p>
</li>
<li><p>6 处，自定义的handler，读事件打印处理好的字符串</p>
</li>
</ul>
<h3 id="2-3-客户端"><a href="#2-3-客户端" class="headerlink" title="2.3 客户端"></a>2.3 客户端</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">Bootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>()) <span class="comment">// 1</span></span><br><span class="line">    .channel(NioSocketChannel.class) <span class="comment">// 2</span></span><br><span class="line">    .handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;Channel&gt;() &#123; <span class="comment">// 3</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(Channel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">StringEncoder</span>()); <span class="comment">// 8</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    .connect(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8080</span>) <span class="comment">// 4</span></span><br><span class="line">    .sync() <span class="comment">// 5</span></span><br><span class="line">    .channel() <span class="comment">// 6</span></span><br><span class="line">    .writeAndFlush(<span class="keyword">new</span> <span class="title class_">Date</span>() + <span class="string">&quot;: hello world!&quot;</span>); <span class="comment">// 7</span></span><br></pre></td></tr></table></figure>

<p>代码解读</p>
<ul>
<li><p>1 处，创建 NioEventLoopGroup，同 Server</p>
</li>
<li><p>2 处，选择客户端 SocketChannel实现类，NioSocketChannel 表示基于 NIO 的客户端实现，其它实现还有</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0007.png"></p>
</li>
<li><p>3 处，添加 SocketChannel 的处理器，ChannelInitializer 处理器（仅执行一次），它的作用是待客户端 SocketChannel 建立连接后，执行 initChannel 以便添加更多的处理器</p>
</li>
<li><p>4 处，指定要连接的服务器和端口</p>
</li>
<li><p>5 处，Netty 中很多方法都是异步的，如 connect，这时需要使用 sync 方法等待 connect 建立连接完毕</p>
</li>
<li><p>6 处，连接建立后获取 channel 对象，它即为通道抽象，可以进行数据读写操作</p>
</li>
<li><p>7 处，写入消息并清空缓冲区</p>
</li>
<li><p>8 处，消息会经过通道 handler 处理，这里是将 String =&gt; ByteBuf 发出</p>
</li>
<li><p>数据经过网络传输，到达服务器端，服务器端 5 和 6 处的 handler 先后被触发，走完一个流程</p>
</li>
</ul>
<h3 id="2-4-流程梳理"><a href="#2-4-流程梳理" class="headerlink" title="2.4 流程梳理"></a>2.4 流程梳理</h3><p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0040.png"></p>
<h4 id="理解"><a href="#理解" class="headerlink" title="理解"></a>理解</h4><blockquote>
<ul>
<li>把 channel 理解为数据的通道</li>
</ul>
<ul>
<li>把 msg 理解为流动的数据，最开始输入是 ByteBuf，但经过 pipeline 的加工，会变成其它类型对象，最后输出又变成 ByteBuf</li>
<li>把 handler 理解为数据的处理工序，addLast()就是加一道工序<ul>
<li>工序有多道，合在一起就是 pipeline，pipeline 负责发布事件（读、读取完成…）传播给每个 handler， handler 对自己感兴趣的事件进行处理（重写了相应事件处理方法）</li>
<li>handler 分 Inbound 和 Outbound 两类</li>
</ul>
</li>
<li>把 eventLoop 理解为处理数据的工人<ul>
<li>工人可以管理多个 channel 的 io 操作，并且一旦工人负责了某个 channel，就要负责到底（绑定）</li>
<li>工人既可以执行 io 操作，也可以进行任务处理，每位工人有任务队列，队列里可以堆放多个 channel 的待处理任务，任务分为普通任务、定时任务</li>
<li>工人按照 pipeline 顺序，依次按照 handler 的规划（代码）处理数据，可以为每道工序指定不同的工人</li>
</ul>
</li>
</ul>
</blockquote>
<h2 id="3-组件"><a href="#3-组件" class="headerlink" title="3. 组件"></a>3. 组件</h2><h3 id="3-1-EventLoop"><a href="#3-1-EventLoop" class="headerlink" title="3.1 EventLoop"></a>3.1 EventLoop</h3><p>事件循环对象</p>
<p>EventLoop 本质是一个单线程执行器（同时维护了一个 Selector），里面有 run 方法处理 Channel 上源源不断的 io 事件。</p>
<p>它的继承关系比较复杂</p>
<ul>
<li>一条线是继承自 j.u.c.ScheduledExecutorService 因此包含了线程池中所有的方法</li>
<li>另一条线是继承自 netty 自己的 OrderedEventExecutor，<ul>
<li>提供了 boolean inEventLoop(Thread thread) 方法判断一个线程是否属于此 EventLoop</li>
<li>提供了 parent 方法来看看自己属于哪个 EventLoopGroup</li>
</ul>
</li>
</ul>
<p>事件循环组</p>
<p>EventLoopGroup 是一组 EventLoop，Channel 一般会调用 EventLoopGroup 的 register 方法来绑定其中一个 EventLoop，后续这个 Channel 上的 io 事件都由此 EventLoop 来处理（保证了 io 事件处理时的线程安全）</p>
<ul>
<li>继承自 netty 自己的 EventExecutorGroup<ul>
<li>实现了 Iterable 接口提供遍历 EventLoop 的能力</li>
<li>另有 next 方法获取集合中下一个 EventLoop</li>
</ul>
</li>
</ul>
<p>以一个简单的实现为例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 内部创建了两个 EventLoop, 每个 EventLoop 维护一个线程，默认是cpu核心数*2</span></span><br><span class="line"><span class="type">DefaultEventLoopGroup</span> <span class="variable">group</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultEventLoopGroup</span>(<span class="number">2</span>);<span class="comment">//处理普通任务和定时任务，NioEventLoopGroup处理io事件、普通任务和定时任务，</span></span><br><span class="line">System.out.println(group.next());</span><br><span class="line">System.out.println(group.next());</span><br><span class="line">System.out.println(group.next());</span><br></pre></td></tr></table></figure>

<p>输出</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">io.netty.channel.DefaultEventLoop@60f82f98</span><br><span class="line">io.netty.channel.DefaultEventLoop@35f983a6</span><br><span class="line">io.netty.channel.DefaultEventLoop@60f82f98</span><br></pre></td></tr></table></figure>

<p>也可以使用 for 循环</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">DefaultEventLoopGroup</span> <span class="variable">group</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultEventLoopGroup</span>(<span class="number">2</span>);</span><br><span class="line"><span class="keyword">for</span> (EventExecutor eventLoop : group) &#123;</span><br><span class="line">    System.out.println(eventLoop);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="NioEventLoop-处理普通任务"><a href="#NioEventLoop-处理普通任务" class="headerlink" title="NioEventLoop 处理普通任务"></a>NioEventLoop 处理普通任务</h4><p>NioEventLoop 除了可以处理 io 事件，同样可以向它提交普通任务</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">NioEventLoopGroup</span> <span class="variable">nioWorkers</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>(<span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">log.debug(<span class="string">&quot;server start...&quot;</span>);</span><br><span class="line">Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">nioWorkers.execute(()-&gt;&#123;</span><br><span class="line">    log.debug(<span class="string">&quot;normal task...&quot;</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>输出</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">22:30:36 [DEBUG] [main] c.i.o.EventLoopTest2 - server start...</span><br><span class="line">22:30:38 [DEBUG] [nioEventLoopGroup-2-1] c.i.o.EventLoopTest2 - normal task...</span><br></pre></td></tr></table></figure>

<blockquote>
<p>可以用来执行耗时较长的任务</p>
<p>可以nioWorkers.next().execute()直接执行任务</p>
</blockquote>
<h4 id="NioEventLoop-处理定时任务"><a href="#NioEventLoop-处理定时任务" class="headerlink" title="NioEventLoop 处理定时任务"></a>NioEventLoop 处理定时任务</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">NioEventLoopGroup</span> <span class="variable">nioWorkers</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>(<span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">log.debug(<span class="string">&quot;server start...&quot;</span>);</span><br><span class="line">Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">nioWorkers.scheduleAtFixedRate(() -&gt; &#123;</span><br><span class="line">    log.debug(<span class="string">&quot;running...&quot;</span>);</span><br><span class="line">&#125;, <span class="number">0</span>, <span class="number">1</span>, TimeUnit.SECONDS);<span class="comment">//初始延迟时间，间隔时间，时间单位</span></span><br></pre></td></tr></table></figure>

<p>输出</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">22:35:15 [DEBUG] [main] c.i.o.EventLoopTest2 - server start...</span><br><span class="line">22:35:17 [DEBUG] [nioEventLoopGroup-2-1] c.i.o.EventLoopTest2 - running...</span><br><span class="line">22:35:18 [DEBUG] [nioEventLoopGroup-2-1] c.i.o.EventLoopTest2 - running...</span><br><span class="line">22:35:19 [DEBUG] [nioEventLoopGroup-2-1] c.i.o.EventLoopTest2 - running...</span><br><span class="line">22:35:20 [DEBUG] [nioEventLoopGroup-2-1] c.i.o.EventLoopTest2 - running...</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<h4 id="NioEventLoop-处理-io-事件"><a href="#NioEventLoop-处理-io-事件" class="headerlink" title="NioEventLoop 处理 io 事件"></a>NioEventLoop 处理 io 事件</h4><p>服务器端两个一个boss两个worker 工人</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">ServerBootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>(<span class="number">1</span>), <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>(<span class="number">2</span>))</span><br><span class="line">    .channel(NioServerSocketChannel.class)</span><br><span class="line">    .childHandler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;NioSocketChannel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(NioSocketChannel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> &#123;</span><br><span class="line">                    <span class="type">ByteBuf</span> <span class="variable">byteBuf</span> <span class="operator">=</span> msg <span class="keyword">instanceof</span> ByteBuf ? ((ByteBuf) msg) : <span class="literal">null</span>;</span><br><span class="line">                    <span class="keyword">if</span> (byteBuf != <span class="literal">null</span>) &#123;</span><br><span class="line">                        log.debug(byteBuf.toString(Charset.defaultCharset()));</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;).bind(<span class="number">8080</span>).sync();</span><br></pre></td></tr></table></figure>

<p>客户端，启动三次，分别修改发送字符串为 zhangsan（第一次），lisi（第二次），wangwu（第三次）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>()</span><br><span class="line">        .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>(<span class="number">1</span>))</span><br><span class="line">        .handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;NioSocketChannel&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(NioSocketChannel ch)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;init...&quot;</span>);</span><br><span class="line">                ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">LoggingHandler</span>(LogLevel.DEBUG));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">        .channel(NioSocketChannel.class).connect(<span class="string">&quot;localhost&quot;</span>, <span class="number">8080</span>)</span><br><span class="line">        .sync()</span><br><span class="line">        .channel();</span><br><span class="line"></span><br><span class="line">    channel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes(<span class="string">&quot;wangwu&quot;</span>.getBytes()));</span><br><span class="line">    Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">    channel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes(<span class="string">&quot;wangwu&quot;</span>.getBytes()));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后输出</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">22:03:34 [DEBUG] [nioEventLoopGroup-3-1] c.i.o.EventLoopTest - zhangsan       </span><br><span class="line">22:03:36 [DEBUG] [nioEventLoopGroup-3-1] c.i.o.EventLoopTest - zhangsan       </span><br><span class="line">22:05:36 [DEBUG] [nioEventLoopGroup-3-2] c.i.o.EventLoopTest - lisi           </span><br><span class="line">22:05:38 [DEBUG] [nioEventLoopGroup-3-2] c.i.o.EventLoopTest - lisi           </span><br><span class="line">22:06:09 [DEBUG] [nioEventLoopGroup-3-1] c.i.o.EventLoopTest - wangwu        </span><br><span class="line">22:06:11 [DEBUG] [nioEventLoopGroup-3-1] c.i.o.EventLoopTest - wangwu         </span><br></pre></td></tr></table></figure>

<p>可以看到两个工人轮流处理 channel，但工人与 channel 之间进行了绑定</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0042.png"></p>
<p>再增加两个非 nio 工人</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">DefaultEventLoopGroup</span> <span class="variable">normalWorkers</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultEventLoopGroup</span>(<span class="number">2</span>);</span><br><span class="line"><span class="keyword">new</span> <span class="title class_">ServerBootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>(<span class="number">1</span>), <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>(<span class="number">2</span>))</span><br><span class="line">    .channel(NioServerSocketChannel.class)</span><br><span class="line">    .childHandler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;NioSocketChannel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(NioSocketChannel ch)</span>  &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">LoggingHandler</span>(LogLevel.DEBUG));</span><br><span class="line">            ch.pipeline().addLast(normalWorkers,<span class="string">&quot;myhandler&quot;</span>,</span><br><span class="line">              <span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> &#123;</span><br><span class="line">                    <span class="type">ByteBuf</span> <span class="variable">byteBuf</span> <span class="operator">=</span> msg <span class="keyword">instanceof</span> ByteBuf ? ((ByteBuf) msg) : <span class="literal">null</span>;</span><br><span class="line">                    <span class="type">ByteBuf</span> <span class="variable">byteBuf</span> <span class="operator">=</span> msg <span class="keyword">instanceof</span> ByteBuf ? ((ByteBuf) msg) : <span class="literal">null</span>;</span><br><span class="line">                    <span class="keyword">if</span> (byteBuf != <span class="literal">null</span>) &#123;</span><br><span class="line">                        log.debug(byteBuf.toString(Charset.defaultCharset()));</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;).bind(<span class="number">8080</span>).sync();</span><br></pre></td></tr></table></figure>

<p>客户端代码不变，启动三次，分别修改发送字符串为 zhangsan（第一次），lisi（第二次），wangwu（第三次）        </p>
<p>nio 工人和 非 nio 工人也分别绑定了 channel（LoggingHandler 由 nio 工人执行，而我们自己的 handler 由非 nio 工人执行）</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0041.png"></p>
<h4 id="handler-执行中如何换人？"><a href="#handler-执行中如何换人？" class="headerlink" title="handler 执行中如何换人？"></a>handler 执行中如何换人？</h4><p>关键代码 <code>io.netty.channel.AbstractChannelHandlerContext#invokeChannelRead()</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">invokeChannelRead</span><span class="params">(<span class="keyword">final</span> AbstractChannelHandlerContext next, Object msg)</span> &#123;</span><br><span class="line">    <span class="keyword">final</span> <span class="type">Object</span> <span class="variable">m</span> <span class="operator">=</span> next.pipeline.touch(ObjectUtil.checkNotNull(msg, <span class="string">&quot;msg&quot;</span>), next);</span><br><span class="line">    <span class="comment">// 下一个 handler 的事件循环是否与当前的事件循环是同一个线程</span></span><br><span class="line">    <span class="type">EventExecutor</span> <span class="variable">executor</span> <span class="operator">=</span> next.executor();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 是，直接调用</span></span><br><span class="line">    <span class="keyword">if</span> (executor.inEventLoop()) &#123;</span><br><span class="line">        next.invokeChannelRead(m);</span><br><span class="line">    &#125; </span><br><span class="line">    <span class="comment">// 不是，将要执行的代码作为任务提交给下一个事件循环处理（换人）</span></span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        executor.execute(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">                next.invokeChannelRead(m);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>如果两个 handler 绑定的是同一个线程（也就是同一个eventLoop)，那么就直接调用</li>
<li>否则，把要调用的代码封装为一个任务对象，由下一个 handler 的线程来调用</li>
</ul>
<h3 id="3-2-Channel"><a href="#3-2-Channel" class="headerlink" title="3.2 Channel"></a>3.2 Channel</h3><p>channel 的主要作用</p>
<ul>
<li>close() 可以用来关闭 channel</li>
<li>closeFuture() 用来处理 channel 的关闭<ul>
<li>sync 方法作用是同步等待 channel 关闭</li>
<li>而 addListener 方法是异步等待 channel 关闭</li>
</ul>
</li>
<li>pipeline() 方法添加处理器</li>
<li>write() 方法将数据写入</li>
<li>writeAndFlush() 方法将数据写入channel并发送出去</li>
</ul>
<h4 id="ChannelFuture"><a href="#ChannelFuture" class="headerlink" title="ChannelFuture"></a>ChannelFuture</h4><p>这时刚才的客户端代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">Bootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>())</span><br><span class="line">    .channel(NioSocketChannel.class)</span><br><span class="line">    .handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;Channel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(Channel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">StringEncoder</span>());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    .connect(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8080</span>)</span><br><span class="line">    .sync()</span><br><span class="line">    .channel()</span><br><span class="line">    .writeAndFlush(<span class="keyword">new</span> <span class="title class_">Date</span>() + <span class="string">&quot;: hello world!&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>现在把它拆开来看</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ChannelFuture</span> <span class="variable">channelFuture</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>())</span><br><span class="line">    .channel(NioSocketChannel.class)</span><br><span class="line">    .handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;Channel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(Channel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">StringEncoder</span>());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    .connect(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8080</span>); <span class="comment">// 1</span></span><br><span class="line"></span><br><span class="line">channelFuture.sync().channel().writeAndFlush(<span class="keyword">new</span> <span class="title class_">Date</span>() + <span class="string">&quot;: hello world!&quot;</span>);</span><br></pre></td></tr></table></figure>

<ul>
<li>1 处返回的是 ChannelFuture 对象，它的作用是利用 channel() 方法来获取 Channel 对象</li>
<li>带有Future的类型都是和异步方法配套使用的</li>
</ul>
<p><strong>注意</strong> connect 方法是异步的，意味着不等连接建立，方法执行就返回了。因此 channelFuture 对象中不能【立刻】获得到正确的 Channel 对象，所以必须得sync()方法<strong>同步处理结果</strong>，线程在sync()方法处会阻塞住，直到nio线程连接建立完毕</p>
<p>实验如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ChannelFuture</span> <span class="variable">channelFuture</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>())</span><br><span class="line">    .channel(NioSocketChannel.class)</span><br><span class="line">    .handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;Channel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(Channel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">StringEncoder</span>());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    .connect(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8080</span>);</span><br><span class="line">System.out.println(channelFuture.channel()); <span class="comment">// 1</span></span><br><span class="line">channelFuture.sync(); <span class="comment">// 2</span></span><br><span class="line">System.out.println(channelFuture.channel()); <span class="comment">// 3</span></span><br></pre></td></tr></table></figure>

<ul>
<li>执行到 1 时，连接未建立，打印 <code>[id: 0x2e1884dd]</code></li>
<li>执行到 2 时，sync 方法是同步等待连接建立完成</li>
<li>执行到 3 时，连接肯定建立了，打印 <code>[id: 0x2e1884dd, L:/127.0.0.1:57191 - R:/127.0.0.1:8080]</code></li>
</ul>
<p>除了用 sync 方法可以让异步操作同步以外，还可以使用addListener方法<strong>异步处理结果</strong>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ChannelFuture</span> <span class="variable">channelFuture</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>())</span><br><span class="line">    .channel(NioSocketChannel.class)</span><br><span class="line">    .handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;Channel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(Channel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">StringEncoder</span>());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    .connect(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8080</span>);</span><br><span class="line">System.out.println(channelFuture.channel()); </span><br><span class="line">channelFuture.addListener(<span class="keyword">new</span> <span class="title class_">ChannelFutureListener</span>()&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">operationComplete</span> <span class="params">(channelFuture future)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> future.channel();</span><br><span class="line">        log.debug(<span class="string">&quot;&#123;&#125;&quot;</span>,channel);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<ul>
<li>ChannelFutureListener 会在连接建立时被调用，会调用operationComplete方法</li>
<li>debug信息显示log.debug(“{}”,channel)也不是在主线程调用，是一个nioEventLoop线程</li>
</ul>
<h4 id="CloseFuture"><a href="#CloseFuture" class="headerlink" title="CloseFuture"></a>CloseFuture</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CloseFutureClient</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        NioEventLoopGroup group <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line">        <span class="type">ChannelFuture</span> <span class="variable">channelFuture</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>()</span><br><span class="line">                .group(group)</span><br><span class="line">                .channel(NioSocketChannel.class)</span><br><span class="line">                .handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;NioSocketChannel&gt;() &#123;</span><br><span class="line">                    <span class="meta">@Override</span> </span><br><span class="line">                    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(NioSocketChannel ch)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                        ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">LoggingHandler</span>(LogLevel.DEBUG));</span><br><span class="line">                        ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">StringEncoder</span>());</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;)</span><br><span class="line">                .connect(<span class="keyword">new</span> <span class="title class_">InetSocketAddress</span>(<span class="string">&quot;localhost&quot;</span>, <span class="number">8080</span>));</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> channelFuture.sync().channel();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            <span class="type">Scanner</span> <span class="variable">scanner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">            <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">                <span class="type">String</span> <span class="variable">line</span> <span class="operator">=</span> scanner.nextLine();</span><br><span class="line">                <span class="keyword">if</span> (<span class="string">&quot;q&quot;</span>.equals(line)) &#123;</span><br><span class="line">                    channel.close(); <span class="comment">//close是异步操作的</span></span><br><span class="line">                    log.debug(<span class="string">&quot;处理关闭之后的操作&quot;</span>)<span class="comment">//将关闭之后的善后逻辑加在这就存在问题</span></span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                channel.writeAndFlush(line);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;input&quot;</span>).start();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取 CloseFuture 对象</span></span><br><span class="line">        <span class="type">ChannelFuture</span> <span class="variable">closeFuture</span> <span class="operator">=</span> channel.closeFuture();</span><br><span class="line">        <span class="comment">//closeFuture.sync();同步处理关闭，</span></span><br><span class="line">        <span class="comment">//log.debug(&quot;处理关闭之后的操作&quot;);保证善后的逻辑一定在channel之后，保证同步的先后顺序</span></span><br><span class="line">        <span class="comment">//异步处理关闭</span></span><br><span class="line">        closeFuture.addListener(<span class="keyword">new</span> <span class="title class_">ChannelFutureListener</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">operationComplete</span><span class="params">(ChannelFuture future)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;处理关闭之后的操作&quot;</span>);</span><br><span class="line">                group.shutdownGracefully();<span class="comment">//优雅关闭EventLoopGroup</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>LoggingHandler的日志信息会显示channel的关闭会在nioEventLoop的线程里异步执行，而log.debug(“处理关闭之后的操作”)在input线程里</li>
<li>closeFuture一样有两种处理方法，同步和异步</li>
</ul>
<h5 id="优雅关闭"><a href="#优雅关闭" class="headerlink" title="优雅关闭"></a>优雅关闭</h5><p>优雅关闭 <code>shutdownGracefully</code> 方法。该方法会首先切换 <code>EventLoopGroup</code> 到关闭状态从而拒绝新的任务的加入，然后在任务队列的任务都处理完成后，停止线程的运行。从而确保整体应用是在正常有序的状态下退出的</p>
<h4 id="异步提升的是什么"><a href="#异步提升的是什么" class="headerlink" title="异步提升的是什么"></a>异步提升的是什么</h4><ul>
<li><p>疑问：为什么不在一个线程中去执行建立连接、去执行关闭 channel，非要用这么复杂的异步方式：比如一个线程发起建立连接，另一个线程去真正建立连接</p>
</li>
<li><p>不能片面认为netty 异步方式用了多线程、多线程就效率高</p>
</li>
</ul>
<p>具体场景，4 个医生给人看病，每个病人花费 20 分钟，而且医生看病的过程中是以病人为单位的，一个病人看完了，才能看下一个病人。</p>
<p>经研究发现，看病可以细分为四个步骤，经拆分后每个步骤需要 5 分钟，如下</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0048.png"></p>
<p>因此可以做如下优化，只有一开始，医生 2、3、4 分别要等待 5、10、15 分钟才能执行工作，但只要后续病人源源不断地来，他们就能够满负荷工作</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0047.png"></p>
<p>要点</p>
<ul>
<li>单线程没法异步提高效率，必须配合多线程、多核 cpu 才能发挥异步的优势</li>
<li>异步并没有缩短响应时间，反而有所增加，</li>
<li>异步后单位时间的吞吐量增加</li>
<li>合理进行任务拆分，也是利用异步的关键</li>
</ul>
<h3 id="3-3-Future-amp-Promise"><a href="#3-3-Future-amp-Promise" class="headerlink" title="3.3 Future &amp; Promise"></a>3.3 Future &amp; Promise</h3><p>在异步处理时，经常用到这两个接口</p>
<p>netty 中的 Future 与 jdk 中的 Future 同名，但是是两个接口，netty 的 Future 继承自 jdk 的 Future，而 Promise 又对 netty Future 进行了扩展</p>
<ul>
<li>jdk Future 只能同步等待任务结束（或成功、或失败）才能得到结果，<strong>相当于线程之间传递信息的容器</strong></li>
<li>netty Future 可以同步等待任务结束得到结果，也可以异步方式得到结果，但都是要等任务结束</li>
<li>netty Promise 不仅有 netty Future 的功能，而且脱离了任务独立存在，只作为两个线程间传递结果的容器</li>
</ul>
<table>
<thead>
<tr>
<th>功能/名称</th>
<th>jdk Future</th>
<th>netty Future</th>
<th>Promise</th>
</tr>
</thead>
<tbody><tr>
<td>cancel</td>
<td>取消任务</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>isCanceled</td>
<td>任务是否取消</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>isDone</td>
<td>任务是否完成，不能区分成功失败</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>get</td>
<td>获取任务结果，阻塞等待</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>getNow</td>
<td>-</td>
<td>获取任务结果，非阻塞，还未产生结果时返回 null</td>
<td>-</td>
</tr>
<tr>
<td>await</td>
<td>-</td>
<td>等待任务结束，如果任务失败，不会抛异常，而是通过 isSuccess 判断</td>
<td>-</td>
</tr>
<tr>
<td>sync</td>
<td>-</td>
<td>等待任务结束，如果任务失败，抛出异常</td>
<td>-</td>
</tr>
<tr>
<td>isSuccess</td>
<td>-</td>
<td>判断任务是否成功</td>
<td>-</td>
</tr>
<tr>
<td>cause</td>
<td>-</td>
<td>获取失败信息，非阻塞，如果没有失败，返回null</td>
<td>-</td>
</tr>
<tr>
<td>addLinstener</td>
<td>-</td>
<td>添加回调，异步接收结果</td>
<td>-</td>
</tr>
<tr>
<td>setSuccess</td>
<td>-</td>
<td>-</td>
<td>设置成功结果</td>
</tr>
<tr>
<td>setFailure</td>
<td>-</td>
<td>-</td>
<td>设置失败结果</td>
</tr>
</tbody></table>
<h4 id="例"><a href="#例" class="headerlink" title="例"></a>例</h4><p><strong>promise同步处理任务</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">DefaultEventLoop</span> <span class="variable">eventLoop</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultEventLoop</span>();</span><br><span class="line">DefaultPromise&lt;Integer&gt; promise = <span class="keyword">new</span> <span class="title class_">DefaultPromise</span>&lt;&gt;(eventLoop);<span class="comment">//也是传递结果的容器</span></span><br><span class="line">eventLoop.execute(()-&gt;&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        promise.setSuccess(<span class="number">10</span>);<span class="comment">//设置成功的结果</span></span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">        promise.setFailure(e);<span class="comment">//可以在结果中传入失败的异常</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line">log.debug(<span class="string">&quot;&#123;&#125;&quot;</span>,promise.getNow()); <span class="comment">// 还没有结果</span></span><br><span class="line">log.debug(<span class="string">&quot;&#123;&#125;&quot;</span>,promise.get());</span><br></pre></td></tr></table></figure>

<p><strong>promise异步处理任务</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">DefaultEventLoop</span> <span class="variable">eventLoop</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultEventLoop</span>();</span><br><span class="line">DefaultPromise&lt;Integer&gt; promise = <span class="keyword">new</span> <span class="title class_">DefaultPromise</span>&lt;&gt;(eventLoop);</span><br><span class="line"><span class="comment">// 设置回调，异步接收结果</span></span><br><span class="line">promise.addListener(future -&gt; &#123;</span><br><span class="line">    log.debug(<span class="string">&quot;&#123;&#125;&quot;</span>,future.getNow());</span><br><span class="line">&#125;);</span><br><span class="line">eventLoop.execute(()-&gt;&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        promise.setSuccess(<span class="number">10</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125; </span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>同步处理任务失败 - await</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">DefaultEventLoop</span> <span class="variable">eventLoop</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultEventLoop</span>();</span><br><span class="line">DefaultPromise&lt;Integer&gt; promise = <span class="keyword">new</span> <span class="title class_">DefaultPromise</span>&lt;&gt;(eventLoop);</span><br><span class="line"></span><br><span class="line">eventLoop.execute(() -&gt; &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">RuntimeException</span> <span class="variable">e</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;error...&quot;</span>);</span><br><span class="line">    promise.setFailure(e);</span><br><span class="line">&#125;);</span><br><span class="line">log.debug(<span class="string">&quot;&#123;&#125;&quot;</span>, promise.getNow());</span><br><span class="line">promise.await(); <span class="comment">// 与 sync 和 get 区别在于，不会抛异常</span></span><br><span class="line">log.debug(<span class="string">&quot;result &#123;&#125;&quot;</span>, (promise.isSuccess() ? promise.getNow() : promise.cause()).toString());</span><br></pre></td></tr></table></figure>

<p><strong>异步处理任务失败</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">DefaultEventLoop</span> <span class="variable">eventLoop</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultEventLoop</span>();</span><br><span class="line">DefaultPromise&lt;Integer&gt; promise = <span class="keyword">new</span> <span class="title class_">DefaultPromise</span>&lt;&gt;(eventLoop);</span><br><span class="line"></span><br><span class="line">promise.addListener(future -&gt; &#123;</span><br><span class="line">    log.debug(<span class="string">&quot;result &#123;&#125;&quot;</span>, (promise.isSuccess() ? promise.getNow() : promise.cause()).toString());</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">eventLoop.execute(() -&gt; &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">RuntimeException</span> <span class="variable">e</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;error...&quot;</span>);</span><br><span class="line">    log.debug(<span class="string">&quot;set failure, &#123;&#125;&quot;</span>, e.toString());</span><br><span class="line">    promise.setFailure(e);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>await 死锁检查</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">DefaultEventLoop</span> <span class="variable">eventLoop</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultEventLoop</span>();</span><br><span class="line">DefaultPromise&lt;Integer&gt; promise = <span class="keyword">new</span> <span class="title class_">DefaultPromise</span>&lt;&gt;(eventLoop);</span><br><span class="line"></span><br><span class="line">eventLoop.submit(()-&gt;&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;1&quot;</span>);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        promise.await();</span><br><span class="line">        <span class="comment">// 注意不能仅捕获 InterruptedException 异常</span></span><br><span class="line">        <span class="comment">// 否则 死锁检查抛出的 BlockingOperationException 会继续向上传播</span></span><br><span class="line">        <span class="comment">// 而提交的任务会被包装为 PromiseTask，它的 run 方法中会 catch 所有异常然后设置为 Promise 的失败结果而不会抛出</span></span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123; </span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(<span class="string">&quot;2&quot;</span>);</span><br><span class="line">&#125;);</span><br><span class="line">eventLoop.submit(()-&gt;&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;3&quot;</span>);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        promise.await();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(<span class="string">&quot;4&quot;</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>输出</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">io.netty.util.concurrent.BlockingOperationException: DefaultPromise@47499c2a(incomplete)</span><br><span class="line">	at io.netty.util.concurrent.DefaultPromise.checkDeadLock(DefaultPromise.java:384)</span><br><span class="line">	at io.netty.util.concurrent.DefaultPromise.await(DefaultPromise.java:212)</span><br><span class="line">	at com.itcast.oio.DefaultPromiseTest.lambda$main$0(DefaultPromiseTest.java:27)</span><br><span class="line">	at io.netty.util.concurrent.PromiseTask$RunnableAdapter.call(PromiseTask.java:38)</span><br><span class="line">	at io.netty.util.concurrent.PromiseTask.run(PromiseTask.java:73)</span><br><span class="line">	at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)</span><br><span class="line">	at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:918)</span><br><span class="line">	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)</span><br><span class="line">	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)</span><br><span class="line">	at java.lang.Thread.run(Thread.java:745)</span><br><span class="line">io.netty.util.concurrent.BlockingOperationException: DefaultPromise@47499c2a(incomplete)</span><br><span class="line">	at io.netty.util.concurrent.DefaultPromise.checkDeadLock(DefaultPromise.java:384)</span><br><span class="line">	at io.netty.util.concurrent.DefaultPromise.await(DefaultPromise.java:212)</span><br><span class="line">	at com.itcast.oio.DefaultPromiseTest.lambda$main$1(DefaultPromiseTest.java:36)</span><br><span class="line">	at io.netty.util.concurrent.PromiseTask$RunnableAdapter.call(PromiseTask.java:38)</span><br><span class="line">	at io.netty.util.concurrent.PromiseTask.run(PromiseTask.java:73)</span><br><span class="line">	at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)</span><br><span class="line">	at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:918)</span><br><span class="line">	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)</span><br><span class="line">	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)</span><br><span class="line">	at java.lang.Thread.run(Thread.java:745)</span><br></pre></td></tr></table></figure>

<h3 id="3-4-Handler-amp-Pipeline"><a href="#3-4-Handler-amp-Pipeline" class="headerlink" title="3.4 Handler &amp; Pipeline"></a>3.4 Handler &amp; Pipeline</h3><p>ChannelHandler 用来处理 Channel 上的各种事件，分为入站、出站两种。所有 ChannelHandler 被连成一串，就是 Pipeline</p>
<ul>
<li>入站处理器通常是 ChannelInboundHandlerAdapter 的子类，主要用来读取客户端数据，写回结果</li>
<li>出站处理器通常是 ChannelOutboundHandlerAdapter 的子类，主要对写回结果进行加工</li>
</ul>
<p>打个比喻，每个 Channel 是一个产品的加工车间，Pipeline 是车间中的流水线，ChannelHandler 就是流水线上的各道工序，ByteBuf 是原材料，经过很多工序的加工：先经过一道道入站工序，再经过一道道出站工序最终变成产品</p>
<p>服务端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">ServerBootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>())</span><br><span class="line">    .channel(NioServerSocketChannel.class)</span><br><span class="line">    .childHandler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;NioSocketChannel&gt;() &#123;</span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(NioSocketChannel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>()&#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> &#123;</span><br><span class="line">                    System.out.println(<span class="number">1</span>);</span><br><span class="line">                    <span class="built_in">super</span>.channelRead(ctx, msg); <span class="comment">// 1</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>()&#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> &#123;</span><br><span class="line">                    System.out.println(<span class="number">2</span>);</span><br><span class="line">                    <span class="built_in">super</span>.channelRead(ctx, msg); <span class="comment">// 2</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>()&#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> &#123;</span><br><span class="line">                    System.out.println(<span class="number">3</span>);</span><br><span class="line">                    ctx.channel().writeAndFlush(msg); <span class="comment">// 3</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelOutboundHandlerAdapter</span>()&#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">write</span><span class="params">(ChannelHandlerContext ctx, Object msg, </span></span><br><span class="line"><span class="params">                                  ChannelPromise promise)</span> &#123;</span><br><span class="line">                    System.out.println(<span class="number">4</span>);</span><br><span class="line">                    <span class="built_in">super</span>.write(ctx, msg, promise); <span class="comment">// 4</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelOutboundHandlerAdapter</span>()&#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">write</span><span class="params">(ChannelHandlerContext ctx, Object msg, </span></span><br><span class="line"><span class="params">                                  ChannelPromise promise)</span> &#123;</span><br><span class="line">                    System.out.println(<span class="number">5</span>);</span><br><span class="line">                    <span class="built_in">super</span>.write(ctx, msg, promise); <span class="comment">// 5</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelOutboundHandlerAdapter</span>()&#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">write</span><span class="params">(ChannelHandlerContext ctx, Object msg, </span></span><br><span class="line"><span class="params">                                  ChannelPromise promise)</span> &#123;</span><br><span class="line">                    System.out.println(<span class="number">6</span>);</span><br><span class="line">                    <span class="built_in">super</span>.write(ctx, msg, promise); <span class="comment">// 6</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    .bind(<span class="number">8080</span>);</span><br></pre></td></tr></table></figure>

<p>客户端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">Bootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>())</span><br><span class="line">    .channel(NioSocketChannel.class)</span><br><span class="line">    .handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;Channel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(Channel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">StringEncoder</span>());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    .connect(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8080</span>)</span><br><span class="line">    .addListener((ChannelFutureListener) future -&gt; &#123;</span><br><span class="line">        future.channel().writeAndFlush(<span class="string">&quot;hello,world&quot;</span>);</span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>

<p>服务器端打印：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">6</span><br><span class="line">5</span><br><span class="line">4</span><br></pre></td></tr></table></figure>

<p>可以看到，ChannelInboundHandlerAdapter 是按照 addLast 的顺序执行的，而 ChannelOutboundHandlerAdapter 是按照 addLast 的逆序执行的。ChannelPipeline 的实现是一个 ChannelHandlerContext（包装了 ChannelHandler） 组成的双向链表</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0008.png"></p>
<ul>
<li>入站处理器中，super.channelRead(ctx, msg)，会处理msg后调用下一个入站处理器，也就是把ChannelHandlerContext传过去，或者调用ctx.fireChannelRead(msg)</li>
<li>出站处理器中 super.write(ctx, msg, promise); 会 **从尾部开始触发上一个出站处理器 **的执行</li>
<li>ctx.channel().writeAndFlush(msg) vs ctx.writeAndFlush(msg)<ul>
<li>都是触发出站处理器的执行</li>
<li>ctx.channel().writeAndFlush(msg) 从尾部开始查找出站处理器</li>
<li>ctx.writeAndFlush(msg) 是从当前节点找上一个出站处理器</li>
<li>3 处的 ctx.channel().writeAndFlush(msg) 如果改为 ctx.writeAndFlush(msg) 仅会打印 1 2 3，因为节点3 之前没有其它出站处理器了</li>
<li>6 处的 ctx.writeAndFlush(msg, promise) 如果改为 ctx.channel().writeAndFlush(msg) 会打印 1 2 3 6 6 6… 因为 ctx.channel().writeAndFlush() 是从尾部开始查找，结果又是节点6 自己</li>
</ul>
</li>
</ul>
<p>服务端 pipeline 触发的原始流程，图中数字代表了处理步骤的先后次序</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0009.png"></p>
<h3 id="3-5-ByteBuf"><a href="#3-5-ByteBuf" class="headerlink" title="3.5 ByteBuf"></a>3.5 ByteBuf</h3><p>是对字节数据的封装</p>
<h4 id="1）创建"><a href="#1）创建" class="headerlink" title="1）创建"></a>1）创建</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ByteBuf</span> <span class="variable">buffer</span> <span class="operator">=</span> ByteBufAllocator.DEFAULT.buffer(<span class="number">10</span>);<span class="comment">//初始容量默认256</span></span><br><span class="line">log(buffer);</span><br></pre></td></tr></table></figure>

<p>上面代码创建了一个默认的 ByteBuf（池化基于直接内存的 ByteBuf），初始容量是 10</p>
<p>输出</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">read index:0 write index:0 capacity:10</span><br></pre></td></tr></table></figure>

<p>其中 log 方法参考如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">log</span><span class="params">(ByteBuf buffer)</span> &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">length</span> <span class="operator">=</span> buffer.readableBytes();</span><br><span class="line">    <span class="type">int</span> <span class="variable">rows</span> <span class="operator">=</span> length / <span class="number">16</span> + (length % <span class="number">15</span> == <span class="number">0</span> ? <span class="number">0</span> : <span class="number">1</span>) + <span class="number">4</span>;</span><br><span class="line">    <span class="type">StringBuilder</span> <span class="variable">buf</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StringBuilder</span>(rows * <span class="number">80</span> * <span class="number">2</span>)</span><br><span class="line">        .append(<span class="string">&quot;read index:&quot;</span>).append(buffer.readerIndex())</span><br><span class="line">        .append(<span class="string">&quot; write index:&quot;</span>).append(buffer.writerIndex())</span><br><span class="line">        .append(<span class="string">&quot; capacity:&quot;</span>).append(buffer.capacity())</span><br><span class="line">        .append(NEWLINE);</span><br><span class="line">    appendPrettyHexDump(buf, buffer);</span><br><span class="line">    System.out.println(buf.toString());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2）直接内存-vs-堆内存"><a href="#2）直接内存-vs-堆内存" class="headerlink" title="2）直接内存 vs 堆内存"></a>2）直接内存 vs 堆内存</h4><p>可以使用下面的代码来创建池化基于堆的 ByteBuf</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ByteBuf</span> <span class="variable">buffer</span> <span class="operator">=</span> ByteBufAllocator.DEFAULT.heapBuffer(<span class="number">10</span>);</span><br></pre></td></tr></table></figure>

<p>也可以使用下面的代码来创建池化基于直接内存的 ByteBuf</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ByteBuf</span> <span class="variable">buffer</span> <span class="operator">=</span> ByteBufAllocator.DEFAULT.directBuffer(<span class="number">10</span>);</span><br></pre></td></tr></table></figure>

<ul>
<li>直接内存创建和销毁的代价昂贵，但读写性能高（少一次内存复制），适合配合池化功能一起用</li>
<li>直接内存对 GC 压力小，因为这部分内存不受 JVM 垃圾回收的管理，但也要注意及时主动释放</li>
<li>默认是直接内存</li>
</ul>
<h4 id="3）池化-vs-非池化"><a href="#3）池化-vs-非池化" class="headerlink" title="3）池化 vs 非池化"></a>3）池化 vs 非池化</h4><p>池化的最大意义在于可以重用 ByteBuf，优点有</p>
<ul>
<li>没有池化，则每次都得创建新的 ByteBuf 实例，这个操作对直接内存代价昂贵，就算是堆内存，也会增加 GC 压力</li>
<li>有了池化，则可以重用池中 ByteBuf 实例，并且采用了与 jemalloc 类似的内存分配算法提升分配效率</li>
<li>高并发时，池化功能更节约内存，减少内存溢出的可能</li>
</ul>
<p>池化功能是否开启，可以通过下面的系统环境变量来设置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-Dio.netty.allocator.type=&#123;unpooled|pooled&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>4.1 以后，非 Android 平台默认启用池化实现，Android 平台启用非池化实现</li>
<li>4.1 之前，池化功能还不成熟，默认是非池化实现</li>
</ul>
<h4 id="4）组成"><a href="#4）组成" class="headerlink" title="4）组成"></a>4）组成</h4><p>ByteBuf 由四部分组成</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0010.png"></p>
<p>最开始读写指针都在 0 位置</p>
<p>与nio的byteBuffer的区别</p>
<ul>
<li><p>读写为两个指针，不用切换读写</p>
</li>
<li><p>可以动态扩容</p>
</li>
</ul>
<h4 id="5）写入"><a href="#5）写入" class="headerlink" title="5）写入"></a>5）写入</h4><p>方法列表，省略一些不重要的方法</p>
<table>
<thead>
<tr>
<th>方法签名</th>
<th>含义</th>
<th>备注</th>
</tr>
</thead>
<tbody><tr>
<td>writeBoolean(boolean value)</td>
<td>写入 boolean 值</td>
<td>用一字节 01|00 代表 true|false</td>
</tr>
<tr>
<td>writeByte(int value)</td>
<td>写入 byte 值</td>
<td></td>
</tr>
<tr>
<td>writeShort(int value)</td>
<td>写入 short 值</td>
<td></td>
</tr>
<tr>
<td>writeInt(int value)</td>
<td>写入 int 值</td>
<td>Big Endian，即 0x250，写入后 00 00 02 50</td>
</tr>
<tr>
<td>writeIntLE(int value)</td>
<td>写入 int 值</td>
<td>Little Endian，即 0x250，写入后 50 02 00 00</td>
</tr>
<tr>
<td>writeLong(long value)</td>
<td>写入 long 值</td>
<td></td>
</tr>
<tr>
<td>writeChar(int value)</td>
<td>写入 char 值</td>
<td></td>
</tr>
<tr>
<td>writeFloat(float value)</td>
<td>写入 float 值</td>
<td></td>
</tr>
<tr>
<td>writeDouble(double value)</td>
<td>写入 double 值</td>
<td></td>
</tr>
<tr>
<td>writeBytes(ByteBuf src)</td>
<td>写入 netty 的 ByteBuf</td>
<td></td>
</tr>
<tr>
<td>writeBytes(byte[] src)</td>
<td>写入 byte[]</td>
<td></td>
</tr>
<tr>
<td>writeBytes(ByteBuffer src)</td>
<td>写入 nio 的 ByteBuffer</td>
<td></td>
</tr>
<tr>
<td>int writeCharSequence(CharSequence sequence, Charset charset)</td>
<td>写入字符串</td>
<td></td>
</tr>
</tbody></table>
<blockquote>
<p>注意</p>
<ul>
<li>这些方法的未指明返回值的，其返回值都是 ByteBuf，意味着可以链式调用</li>
<li>网络传输，默认习惯是 Big Endian</li>
<li>还有一类方法是 set 开头的一系列方法，也可以写入数据，但不会改变写指针位置</li>
</ul>
</blockquote>
<h4 id="6）扩容"><a href="#6）扩容" class="headerlink" title="6）扩容"></a>6）扩容</h4><p>扩容规则是</p>
<ul>
<li>如何写入后数据大小未超过 512，则选择下一个 16 的整数倍，例如写入后大小为 12 ，则扩容后 capacity 是 16</li>
<li>如果写入后数据大小超过 512，则选择下一个 2^n，例如写入后大小为 513，则扩容后 capacity 是 2^10=1024（2^9=512 已经不够了）</li>
<li>扩容不能超过 max capacity 会报错</li>
</ul>
<h4 id="7）读取"><a href="#7）读取" class="headerlink" title="7）读取"></a>7）读取</h4><p>例如读了 4 次，每次一个字节</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">System.out.println(buffer.readByte());</span><br><span class="line">System.out.println(buffer.readByte());</span><br><span class="line">System.out.println(buffer.readByte());</span><br><span class="line">System.out.println(buffer.readByte());</span><br><span class="line">log(buffer);</span><br></pre></td></tr></table></figure>

<p>读过的内容，就属于废弃部分了，再读只能读那些尚未读取的部分</p>
<p>读取整数，读指针就会移动4个字节</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">System.out.println(buffer.readInt());</span><br></pre></td></tr></table></figure>

<p>如果需要重复读取 int 整数 ，怎么办？</p>
<p>可以在 read 前先做个标记 mark</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">buffer.markReaderIndex();</span><br><span class="line">System.out.println(buffer.readInt());</span><br><span class="line"><span class="comment">//这时要重复读取的话，重置到标记位置 reset</span></span><br><span class="line">buffer.resetReaderIndex();</span><br></pre></td></tr></table></figure>

<p>还有种办法是采用 get 开头的一系列方法，这些方法不会改变 read index</p>
<h4 id="8）retain-amp-release"><a href="#8）retain-amp-release" class="headerlink" title="8）retain &amp; release"></a>8）retain &amp; release</h4><p>由于 Netty 中有堆外内存的 ByteBuf 实现，堆外内存最好是手动来释放，而不是等 GC 垃圾回收。</p>
<ul>
<li>UnpooledHeapByteBuf 使用的是 JVM 内存，只需等 GC 回收内存即可</li>
<li>UnpooledDirectByteBuf 使用的就是直接内存了，需要特殊的方法来回收内存</li>
<li>PooledByteBuf 和它的子类使用了池化机制，需要更复杂的规则来回收内存</li>
</ul>
<blockquote>
<p>回收内存的源码实现，关注下面方法的不同实现</p>
<p><code>protected abstract void deallocate()</code></p>
</blockquote>
<p>Netty 采用了引用计数法来控制回收内存，每个 ByteBuf 都实现了 ReferenceCounted 接口</p>
<ul>
<li>每个 ByteBuf 对象的初始计数为 1</li>
<li>调用 release 方法计数减 1，如果计数为 0，ByteBuf 内存被回收</li>
<li>调用 retain 方法计数加 1，表示调用者没用完之前，其它 handler 即使调用了 release 也不会造成回收</li>
<li>当计数为 0 时，底层内存会被回收，这时即使 ByteBuf 对象还在，其各个方法均无法正常使用</li>
</ul>
<p>谁来负责 release 呢？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ByteBuf</span> <span class="variable">buf</span> <span class="operator">=</span> ...</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    ...</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    buf.release();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因为 pipeline 的存在，一般需要将 ByteBuf 传递给下一个 ChannelHandler，如果在 finally 中 release 了，就失去了传递性（当然，如果在这个 ChannelHandler 内这个 ByteBuf 已完成了它的使命，那么便无须再传递）</p>
<p>基本规则是，<strong>谁是最后使用者，谁负责 release</strong></p>
<ul>
<li>起点，对于 NIO 实现来讲，在 io.netty.channel.nio.AbstractNioByteChannel.NioByteUnsafe#read 方法中首次创建 ByteBuf 放入 pipeline（line 163 pipeline.fireChannelRead(byteBuf)）</li>
<li>入站 ByteBuf 处理原则<ul>
<li>对原始 ByteBuf 不做处理，调用 ctx.fireChannelRead(msg) 向后传递，这时无须 release</li>
<li>将原始 ByteBuf 转换为其它类型的 Java 对象，这时 ByteBuf 就没用了，必须 release</li>
<li>如果不调用 ctx.fireChannelRead(msg) 向后传递，那么也必须 release</li>
<li>注意各种异常，如果 ByteBuf 没有成功传递到下一个 ChannelHandler，必须 release</li>
<li>假设消息一直向后传，那么 TailContext 会负责释放未处理消息（原始的 ByteBuf）</li>
</ul>
</li>
<li>出站 ByteBuf 处理原则<ul>
<li>出站消息最终都会转为 ByteBuf 输出，一直向前传，由 HeadContext flush 后 release</li>
</ul>
</li>
<li>异常处理原则<ul>
<li>有时候不清楚 ByteBuf 被引用了多少次，但又必须彻底释放，可以循环调用 release 直到返回 true</li>
</ul>
</li>
</ul>
<p>TailContext 释放未处理消息具体代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// io.netty.util.ReferenceCountUtil#release(java.lang.Object)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="type">boolean</span> <span class="title function_">release</span><span class="params">(Object msg)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (msg <span class="keyword">instanceof</span> ReferenceCounted) &#123;</span><br><span class="line">        <span class="keyword">return</span> ((ReferenceCounted) msg).release();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="9）slice"><a href="#9）slice" class="headerlink" title="9）slice"></a>9）slice</h4><p>【零拷贝】的体现之一，对原始 ByteBuf 进行切片成多个 ByteBuf，切片后的 ByteBuf 并没有发生内存复制，还是使用原始 ByteBuf 的内存，切片后的 ByteBuf 维护独立的 read，write 指针</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0011.png"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">buf.slice(index,length)</span><br></pre></td></tr></table></figure>

<ul>
<li><p>无参 slice 是从原始 ByteBuf 的 read index 到 write index 之间的内容进行切片，切片后的 max capacity 被固定为这个区间的大小，因此不能追加 write</p>
</li>
<li><p>如果 slice 的内容发生了更改原始 ByteBuf 也会受影响，因为底层都是同一块内存</p>
</li>
<li><p>原始内存release释放后切片也会被释放</p>
<p>通常让切片buf调用retain()，计数+1，从而正确的保留切片内存，原始</p>
</li>
</ul>
<h4 id="10）duplicate"><a href="#10）duplicate" class="headerlink" title="10）duplicate"></a>10）duplicate</h4><p>【零拷贝】的体现之一，就好比截取了原始 ByteBuf 所有内容，并且没有 max capacity 的限制，也是与原始 ByteBuf 使用同一块底层内存，只是读写指针是独立的</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0012.png"></p>
<h4 id="11）copy"><a href="#11）copy" class="headerlink" title="11）copy"></a>11）copy</h4><p>会将底层内存数据进行深拷贝，因此无论读写，都与原始 ByteBuf 无关</p>
<h4 id="12）CompositeByteBuf"><a href="#12）CompositeByteBuf" class="headerlink" title="12）CompositeByteBuf"></a>12）CompositeByteBuf</h4><p>【零拷贝】的体现之一，可以将多个 ByteBuf 合并为一个逻辑上的 ByteBuf，避免拷贝</p>
<p>有两个 ByteBuf 如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ByteBuf</span> <span class="variable">buf1</span> <span class="operator">=</span> ByteBufAllocator.DEFAULT.buffer(<span class="number">5</span>);</span><br><span class="line">buf1.writeBytes(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>&#125;);</span><br><span class="line"><span class="type">ByteBuf</span> <span class="variable">buf2</span> <span class="operator">=</span> ByteBufAllocator.DEFAULT.buffer(<span class="number">5</span>);</span><br><span class="line">buf2.writeBytes(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>&#125;);</span><br></pre></td></tr></table></figure>

<p>现在需要一个新的 ByteBuf，内容来自于刚才的 buf1 和 buf2，如何实现？</p>
<p>方法1：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ByteBuf</span> <span class="variable">buf3</span> <span class="operator">=</span> ByteBufAllocator.DEFAULT</span><br><span class="line">    .buffer(buf1.readableBytes()+buf2.readableBytes());</span><br><span class="line">buf3.writeBytes(buf1);</span><br><span class="line">buf3.writeBytes(buf2);</span><br></pre></td></tr></table></figure>

<p>这种方法不太好，因为进行了数据的内存复制操作</p>
<p>方法2：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">CompositeByteBuf</span> <span class="variable">buf3</span> <span class="operator">=</span> ByteBufAllocator.DEFAULT.compositeBuffer();</span><br><span class="line"><span class="comment">// true 表示增加新的 ByteBuf 自动递增 write index, 否则 write index 会始终为 0</span></span><br><span class="line">buf3.addComponents(<span class="literal">true</span>, buf1, buf2);</span><br></pre></td></tr></table></figure>

<p>CompositeByteBuf 是一个组合的 ByteBuf，它内部维护了一个 Component 数组，每个 Component 管理一个 ByteBuf，记录了这个 ByteBuf 相对于整体偏移量等信息，代表着整体中某一段的数据。</p>
<ul>
<li>优点，对外是一个虚拟视图，组合这些 ByteBuf 不会产生内存复制</li>
<li>缺点，复杂了很多，多次操作会带来性能的损耗</li>
</ul>
<h4 id="13）Unpooled"><a href="#13）Unpooled" class="headerlink" title="13）Unpooled"></a>13）Unpooled</h4><p>Unpooled 是一个工具类，类如其名，提供了非池化的 ByteBuf 创建、组合、复制等操作</p>
<p>这里仅介绍其跟【零拷贝】相关的 wrappedBuffer 方法，可以用来包装 ByteBuf</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ByteBuf</span> <span class="variable">buf1</span> <span class="operator">=</span> ByteBufAllocator.DEFAULT.buffer(<span class="number">5</span>);</span><br><span class="line">buf1.writeBytes(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>&#125;);</span><br><span class="line"><span class="type">ByteBuf</span> <span class="variable">buf2</span> <span class="operator">=</span> ByteBufAllocator.DEFAULT.buffer(<span class="number">5</span>);</span><br><span class="line">buf2.writeBytes(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 当包装 ByteBuf 个数超过一个时, 底层使用了 CompositeByteBuf</span></span><br><span class="line"><span class="type">ByteBuf</span> <span class="variable">buf</span> <span class="operator">=</span> Unpooled.wrappedBuffer(buf1, buf2);</span><br></pre></td></tr></table></figure>

<p>也可以用来包装普通字节数组，底层也不会有拷贝操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ByteBuf</span> <span class="variable">buf4</span> <span class="operator">=</span> Unpooled.wrappedBuffer(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;, <span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>&#125;);</span><br><span class="line">System.out.println(buf4.getClass());</span><br></pre></td></tr></table></figure>

<h4 id="ByteBuf-优势"><a href="#ByteBuf-优势" class="headerlink" title="ByteBuf 优势"></a>ByteBuf 优势</h4><ul>
<li>池化 - 可以重用池中 ByteBuf 实例，更节约内存，减少内存溢出的可能</li>
<li>读写指针分离，不需要像 ByteBuffer 一样切换读写模式</li>
<li>可以自动扩容</li>
<li>支持链式调用，使用更流畅</li>
<li>很多地方体现零拷贝，例如 slice、duplicate、CompositeByteBuf</li>
</ul>
<h2 id="4-双向通信"><a href="#4-双向通信" class="headerlink" title="4. 双向通信"></a>4. 双向通信</h2><p>实现一个 echo server</p>
<p>编写 server</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">ServerBootstrap</span>()</span><br><span class="line">    .group(<span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>())</span><br><span class="line">    .channel(NioServerSocketChannel.class)</span><br><span class="line">    .childHandler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;NioSocketChannel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(NioSocketChannel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>()&#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> &#123;</span><br><span class="line">                    <span class="type">ByteBuf</span> <span class="variable">buffer</span> <span class="operator">=</span> (ByteBuf) msg;</span><br><span class="line">                    System.out.println(buffer.toString(Charset.defaultCharset()));</span><br><span class="line"></span><br><span class="line">                    <span class="comment">// 建议使用 ctx.alloc() 创建 ByteBuf</span></span><br><span class="line">                    <span class="type">ByteBuf</span> <span class="variable">response</span> <span class="operator">=</span> ctx.alloc().buffer();</span><br><span class="line">                    response.writeBytes(buffer);</span><br><span class="line">                    ctx.writeAndFlush(response);</span><br><span class="line"></span><br><span class="line">                    <span class="comment">// 思考：需要释放 buffer 吗</span></span><br><span class="line">                    <span class="comment">// 思考：需要释放 response 吗</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;).bind(<span class="number">8080</span>);</span><br></pre></td></tr></table></figure>

<p>编写 client</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">NioEventLoopGroup</span> <span class="variable">group</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line"><span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>()</span><br><span class="line">    .group(group)</span><br><span class="line">    .channel(NioSocketChannel.class)</span><br><span class="line">    .handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;NioSocketChannel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(NioSocketChannel ch)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">StringEncoder</span>());</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> &#123;</span><br><span class="line">                    <span class="type">ByteBuf</span> <span class="variable">buffer</span> <span class="operator">=</span> (ByteBuf) msg;</span><br><span class="line">                    System.out.println(buffer.toString(Charset.defaultCharset()));</span><br><span class="line"></span><br><span class="line">                    <span class="comment">// 思考：需要释放 buffer 吗</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;).connect(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8080</span>).sync().channel();</span><br><span class="line"></span><br><span class="line">channel.closeFuture().addListener(future -&gt; &#123;</span><br><span class="line">    group.shutdownGracefully();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">    <span class="type">Scanner</span> <span class="variable">scanner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">    <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">line</span> <span class="operator">=</span> scanner.nextLine();</span><br><span class="line">        <span class="keyword">if</span> (<span class="string">&quot;q&quot;</span>.equals(line)) &#123;</span><br><span class="line">            channel.close();</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        channel.writeAndFlush(line);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;).start();</span><br></pre></td></tr></table></figure>

<h3 id="读和写的误解"><a href="#读和写的误解" class="headerlink" title="读和写的误解"></a>读和写的误解</h3><p>我最初在认识上有这样的误区，认为只有在 netty，nio 这样的多路复用 IO 模型时，读写才不会相互阻塞，才可以实现高效的双向通信，但实际上，Java Socket 是全双工的：在任意时刻，线路上存在<code>A 到 B</code> 和 <code>B 到 A</code> 的双向信号传输。即使是阻塞 IO，读和写是可以同时进行的，只要分别采用读线程和写线程即可，读不会阻塞写、写也不会阻塞读</p>
<p>例如</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestServer</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="type">ServerSocket</span> <span class="variable">ss</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ServerSocket</span>(<span class="number">8888</span>);</span><br><span class="line">        <span class="type">Socket</span> <span class="variable">s</span> <span class="operator">=</span> ss.accept();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="type">BufferedReader</span> <span class="variable">reader</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BufferedReader</span>(<span class="keyword">new</span> <span class="title class_">InputStreamReader</span>(s.getInputStream()));</span><br><span class="line">                <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">                    System.out.println(reader.readLine());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="type">BufferedWriter</span> <span class="variable">writer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BufferedWriter</span>(<span class="keyword">new</span> <span class="title class_">OutputStreamWriter</span>(s.getOutputStream()));</span><br><span class="line">                <span class="comment">// 例如在这个位置加入 thread 级别断点，可以发现即使不写入数据，也不妨碍前面线程读取客户端数据</span></span><br><span class="line">                <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">                    writer.write(String.valueOf(i));</span><br><span class="line">                    writer.newLine();</span><br><span class="line">                    writer.flush();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>客户端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestClient</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="type">Socket</span> <span class="variable">s</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Socket</span>(<span class="string">&quot;localhost&quot;</span>, <span class="number">8888</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="type">BufferedReader</span> <span class="variable">reader</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BufferedReader</span>(<span class="keyword">new</span> <span class="title class_">InputStreamReader</span>(s.getInputStream()));</span><br><span class="line">                <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">                    System.out.println(reader.readLine());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="type">BufferedWriter</span> <span class="variable">writer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BufferedWriter</span>(<span class="keyword">new</span> <span class="title class_">OutputStreamWriter</span>(s.getOutputStream()));</span><br><span class="line">                <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">                    writer.write(String.valueOf(i));</span><br><span class="line">                    writer.newLine();</span><br><span class="line">                    writer.flush();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="进阶"><a href="#进阶" class="headerlink" title="进阶"></a>进阶</h1><h2 id="1-粘包与半包"><a href="#1-粘包与半包" class="headerlink" title="1. 粘包与半包"></a>1. 粘包与半包</h2><h3 id="1-1-粘包现象"><a href="#1-1-粘包现象" class="headerlink" title="1.1 粘包现象"></a>1.1 粘包现象</h3><p>服务端代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HelloWorldServer</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Logger</span> <span class="variable">log</span> <span class="operator">=</span> LoggerFactory.getLogger(HelloWorldServer.class);</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">start</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">NioEventLoopGroup</span> <span class="variable">boss</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>(<span class="number">1</span>);</span><br><span class="line">        <span class="type">NioEventLoopGroup</span> <span class="variable">worker</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">ServerBootstrap</span> <span class="variable">serverBootstrap</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ServerBootstrap</span>();</span><br><span class="line">            serverBootstrap.channel(NioServerSocketChannel.class);</span><br><span class="line">            serverBootstrap.group(boss, worker);</span><br><span class="line">            serverBootstrap.childHandler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;SocketChannel&gt;() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(SocketChannel ch)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                    ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">LoggingHandler</span>(LogLevel.DEBUG));</span><br><span class="line">                    ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>() &#123;</span><br><span class="line">                        <span class="meta">@Override</span></span><br><span class="line">                        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                            log.debug(<span class="string">&quot;connected &#123;&#125;&quot;</span>, ctx.channel());</span><br><span class="line">                            <span class="built_in">super</span>.channelActive(ctx);</span><br><span class="line">                        &#125;</span><br><span class="line"></span><br><span class="line">                        <span class="meta">@Override</span></span><br><span class="line">                        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelInactive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                            log.debug(<span class="string">&quot;disconnect &#123;&#125;&quot;</span>, ctx.channel());</span><br><span class="line">                            <span class="built_in">super</span>.channelInactive(ctx);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            <span class="type">ChannelFuture</span> <span class="variable">channelFuture</span> <span class="operator">=</span> serverBootstrap.bind(<span class="number">8080</span>);</span><br><span class="line">            log.debug(<span class="string">&quot;&#123;&#125; binding...&quot;</span>, channelFuture.channel());</span><br><span class="line">            channelFuture.sync();</span><br><span class="line">            log.debug(<span class="string">&quot;&#123;&#125; bound...&quot;</span>, channelFuture.channel());</span><br><span class="line">            channelFuture.channel().closeFuture().sync();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            log.error(<span class="string">&quot;server error&quot;</span>, e);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            boss.shutdownGracefully();</span><br><span class="line">            worker.shutdownGracefully();</span><br><span class="line">            log.debug(<span class="string">&quot;stoped&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">HelloWorldServer</span>().start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>客户端代码希望发送 10 个消息，每个消息是 16 字节</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HelloWorldClient</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Logger</span> <span class="variable">log</span> <span class="operator">=</span> LoggerFactory.getLogger(HelloWorldClient.class);</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">NioEventLoopGroup</span> <span class="variable">worker</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">Bootstrap</span> <span class="variable">bootstrap</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>();</span><br><span class="line">            bootstrap.channel(NioSocketChannel.class);</span><br><span class="line">            bootstrap.group(worker);</span><br><span class="line">            bootstrap.handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;SocketChannel&gt;() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(SocketChannel ch)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                    log.debug(<span class="string">&quot;connetted...&quot;</span>);</span><br><span class="line">                    ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>() &#123;</span><br><span class="line">                        <span class="meta">@Override</span></span><br><span class="line">                        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                            log.debug(<span class="string">&quot;sending...&quot;</span>);</span><br><span class="line">                            <span class="type">Random</span> <span class="variable">r</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Random</span>();</span><br><span class="line">                            <span class="type">char</span> <span class="variable">c</span> <span class="operator">=</span> <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">                            <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">                                <span class="type">ByteBuf</span> <span class="variable">buffer</span> <span class="operator">=</span> ctx.alloc().buffer();</span><br><span class="line">                                buffer.writeBytes(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>, <span class="number">11</span>, <span class="number">12</span>, <span class="number">13</span>, <span class="number">14</span>, <span class="number">15</span>&#125;);</span><br><span class="line">                                ctx.writeAndFlush(buffer);</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            <span class="type">ChannelFuture</span> <span class="variable">channelFuture</span> <span class="operator">=</span> bootstrap.connect(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8080</span>).sync();</span><br><span class="line">            channelFuture.channel().closeFuture().sync();</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            log.error(<span class="string">&quot;client error&quot;</span>, e);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            worker.shutdownGracefully();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>服务器端的某次输出，可以看到一次就接收了 160 个字节，而非分 10 次接收</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">08:24:46 [DEBUG] [main] c.i.n.HelloWorldServer - [id: 0x81e0fda5] binding...</span><br><span class="line">08:24:46 [DEBUG] [main] c.i.n.HelloWorldServer - [id: 0x81e0fda5, L:/0:0:0:0:0:0:0:0:8080] bound...</span><br><span class="line">08:24:55 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x94132411, L:/127.0.0.1:8080 - R:/127.0.0.1:58177] REGISTERED</span><br><span class="line">08:24:55 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x94132411, L:/127.0.0.1:8080 - R:/127.0.0.1:58177] ACTIVE</span><br><span class="line">08:24:55 [DEBUG] [nioEventLoopGroup-3-1] c.i.n.HelloWorldServer - connected [id: 0x94132411, L:/127.0.0.1:8080 - R:/127.0.0.1:58177]</span><br><span class="line">08:24:55 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x94132411, L:/127.0.0.1:8080 - R:/127.0.0.1:58177] READ: 160B</span><br><span class="line">         +-------------------------------------------------+</span><br><span class="line">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |</span><br><span class="line">+--------+-------------------------------------------------+----------------+</span><br><span class="line">|00000000| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">|00000010| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">|00000020| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">|00000030| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">|00000040| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">|00000050| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">|00000060| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">|00000070| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">|00000080| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">|00000090| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">+--------+-------------------------------------------------+----------------+</span><br><span class="line">08:24:55 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x94132411, L:/127.0.0.1:8080 - R:/127.0.0.1:58177] READ COMPLETE</span><br></pre></td></tr></table></figure>

<h3 id="1-2-半包现象"><a href="#1-2-半包现象" class="headerlink" title="1.2 半包现象"></a>1.2 半包现象</h3><p>客户端代码希望发送 1 个消息，这个消息是 160 字节，代码改为</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">ByteBuf</span> <span class="variable">buffer</span> <span class="operator">=</span> ctx.alloc().buffer();</span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">    buffer.writeBytes(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>, <span class="number">11</span>, <span class="number">12</span>, <span class="number">13</span>, <span class="number">14</span>, <span class="number">15</span>&#125;);</span><br><span class="line">&#125;</span><br><span class="line">ctx.writeAndFlush(buffer);</span><br></pre></td></tr></table></figure>

<p>为现象明显，服务端修改一下接收缓冲区，其它代码不变</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">serverBootstrap.option(ChannelOption.SO_RCVBUF, <span class="number">10</span>);</span><br></pre></td></tr></table></figure>

<p>服务器端的某次输出，可以看到接收的消息被分为两节，第一次 20 字节，第二次 140 字节</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">08:43:49 [DEBUG] [main] c.i.n.HelloWorldServer - [id: 0x4d6c6a84] binding...</span><br><span class="line">08:43:49 [DEBUG] [main] c.i.n.HelloWorldServer - [id: 0x4d6c6a84, L:/0:0:0:0:0:0:0:0:8080] bound...</span><br><span class="line">08:44:23 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] REGISTERED</span><br><span class="line">08:44:23 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] ACTIVE</span><br><span class="line">08:44:23 [DEBUG] [nioEventLoopGroup-3-1] c.i.n.HelloWorldServer - connected [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221]</span><br><span class="line">08:44:24 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] READ: 20B</span><br><span class="line">         +-------------------------------------------------+</span><br><span class="line">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |</span><br><span class="line">+--------+-------------------------------------------------+----------------+</span><br><span class="line">|00000000| 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................|</span><br><span class="line">|00000010| 00 01 02 03                                     |....            |</span><br><span class="line">+--------+-------------------------------------------------+----------------+</span><br><span class="line">08:44:24 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] READ COMPLETE</span><br><span class="line">08:44:24 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] READ: 140B</span><br><span class="line">         +-------------------------------------------------+</span><br><span class="line">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |</span><br><span class="line">+--------+-------------------------------------------------+----------------+</span><br><span class="line">|00000000| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|</span><br><span class="line">|00000010| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|</span><br><span class="line">|00000020| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|</span><br><span class="line">|00000030| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|</span><br><span class="line">|00000040| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|</span><br><span class="line">|00000050| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|</span><br><span class="line">|00000060| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|</span><br><span class="line">|00000070| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 01 02 03 |................|</span><br><span class="line">|00000080| 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f             |............    |</span><br><span class="line">+--------+-------------------------------------------------+----------------+</span><br><span class="line">08:44:24 [DEBUG] [nioEventLoopGroup-3-1] i.n.h.l.LoggingHandler - [id: 0x1719abf7, L:/127.0.0.1:8080 - R:/127.0.0.1:59221] READ COMPLETE</span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong>注意</strong></p>
<p>serverBootstrap.option(ChannelOption.SO_RCVBUF, 10) 影响的底层接收缓冲区（即滑动窗口）大小，仅决定了 netty 读取的最小单位，netty 实际每次读取的一般是它的整数倍</p>
</blockquote>
<h3 id="1-3-现象分析"><a href="#1-3-现象分析" class="headerlink" title="1.3 现象分析"></a>1.3 现象分析</h3><p>粘包</p>
<ul>
<li>现象，发送 abc def，接收 abcdef</li>
<li>原因<ul>
<li>应用层：接收方 ByteBuf 设置太大（Netty 默认 1024）</li>
<li>滑动窗口：假设发送方 256 bytes 表示一个完整报文，但由于接收方处理不及时且窗口大小足够大，这 256 bytes 字节就会缓冲在接收方的滑动窗口中，当滑动窗口中缓冲了多个报文就会粘包</li>
<li>Nagle 算法：会造成粘包</li>
</ul>
</li>
</ul>
<p>半包</p>
<ul>
<li>现象，发送 abcdef，接收 abc def</li>
<li>原因<ul>
<li>应用层：接收方 ByteBuf 小于实际发送数据量</li>
<li>滑动窗口：假设接收方的窗口只剩了 128 bytes，发送方的报文大小是 256 bytes，这时放不下了，只能先发送前 128 bytes，等待 ack 后才能发送剩余部分，这就造成了半包</li>
<li>MSS 限制：当发送的数据超过 MSS 限制后，会将数据切分发送，就会造成半包</li>
</ul>
</li>
</ul>
<p>本质是因为 TCP 是流式协议，消息无边界</p>
<blockquote>
<p>滑动窗口</p>
<ul>
<li><p>TCP 以一个段（segment）为单位，每发送一个段就需要进行一次确认应答（ack）处理，但如果这么做，缺点是包的往返时间越长性能就越差</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0049.png"></p>
</li>
</ul>
<ul>
<li><p>为了解决此问题，引入了窗口概念，窗口大小即决定了无需等待应答而可以继续发送的数据最大值</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0051.png"></p>
</li>
<li><p>窗口实际就起到一个缓冲区的作用，同时也能起到流量控制的作用</p>
<ul>
<li>图中深色的部分即要发送的数据，高亮的部分即窗口</li>
<li>窗口内的数据才允许被发送，当应答未到达前，窗口必须停止滑动</li>
<li>如果 1001~2000 这个段的数据 ack 回来了，窗口就可以向前滑动</li>
<li>接收方也会维护一个窗口，只有落在窗口内的数据才能允许接收</li>
</ul>
</li>
</ul>
</blockquote>
<blockquote>
<p> MSS 限制</p>
<ul>
<li><p>链路层对一次能够发送的最大数据有限制，这个限制称之为 MTU（maximum transmission unit），不同的链路设备的 MTU 值也有所不同，例如</p>
</li>
<li><p>以太网的 MTU 是 1500</p>
</li>
<li><p>FDDI（光纤分布式数据接口）的 MTU 是 4352</p>
</li>
<li><p>本地回环地址的 MTU 是 65535 - 本地测试不走网卡</p>
</li>
<li><p>MSS 是最大段长度（maximum segment size），它是 MTU 刨去 tcp 头和 ip 头后剩余能够作为数据传输的字节数</p>
</li>
<li><p>ipv4 tcp 头占用 20 bytes，ip 头占用 20 bytes，因此以太网 MSS 的值为 1500 - 40 = 1460</p>
</li>
<li><p>TCP 在传递大量数据时，会按照 MSS 大小将数据进行分割发送</p>
</li>
<li><p>MSS 的值在三次握手时通知对方自己 MSS 的值，然后在两者之间选择一个小值作为 MSS</p>
</li>
</ul>
</blockquote>
<blockquote>
<p>Nagle 算法</p>
<ul>
<li>即使发送一个字节，也需要加入 tcp 头和 ip 头，也就是总字节数会使用 41 bytes，非常不经济。因此为了提高网络利用率，tcp 希望尽可能发送足够大的数据，这就是 Nagle 算法产生的缘由</li>
<li>该算法是指发送端即使还有应该发送的数据，但如果这部分数据很少的话，则进行延迟发送<ul>
<li>如果 SO_SNDBUF 的数据达到 MSS，则需要发送</li>
<li>如果 SO_SNDBUF 中含有 FIN（表示需要连接关闭）这时将剩余数据发送，再关闭</li>
<li>如果 TCP_NODELAY = true，则需要发送</li>
<li>已发送的数据都收到 ack 时，则需要发送</li>
<li>上述条件不满足，但发生超时（一般为 200ms）则需要发送</li>
<li>除上述情况，延迟发送</li>
</ul>
</li>
</ul>
</blockquote>
<h3 id="1-4-解决方案"><a href="#1-4-解决方案" class="headerlink" title="1.4 解决方案"></a>1.4 解决方案</h3><ol>
<li>短链接，发一个包建立一次连接，这样连接建立到连接断开之间就是消息的边界，缺点效率太低</li>
<li>每一条消息采用固定长度，缺点浪费空间</li>
<li>每一条消息采用分隔符，例如 \n，缺点需要转义</li>
<li>每一条消息分为 head 和 body，head 中包含 body 的长度</li>
</ol>
<h4 id="方法1，短链接"><a href="#方法1，短链接" class="headerlink" title="方法1，短链接"></a>方法1，短链接</h4><p>以解决粘包为例</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HelloWorldClient</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Logger</span> <span class="variable">log</span> <span class="operator">=</span> LoggerFactory.getLogger(HelloWorldClient.class);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">// 分 10 次发送</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">            send();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">send</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">NioEventLoopGroup</span> <span class="variable">worker</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">Bootstrap</span> <span class="variable">bootstrap</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>();</span><br><span class="line">            bootstrap.channel(NioSocketChannel.class);</span><br><span class="line">            bootstrap.group(worker);</span><br><span class="line">            bootstrap.handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;SocketChannel&gt;() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(SocketChannel ch)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                    log.debug(<span class="string">&quot;conneted...&quot;</span>);</span><br><span class="line">                    ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">LoggingHandler</span>(LogLevel.DEBUG));</span><br><span class="line">                    ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>() &#123;</span><br><span class="line">                        <span class="meta">@Override</span></span><br><span class="line">                        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                            log.debug(<span class="string">&quot;sending...&quot;</span>);</span><br><span class="line">                            <span class="type">ByteBuf</span> <span class="variable">buffer</span> <span class="operator">=</span> ctx.alloc().buffer();</span><br><span class="line">                            buffer.writeBytes(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>, <span class="number">11</span>, <span class="number">12</span>, <span class="number">13</span>, <span class="number">14</span>, <span class="number">15</span>&#125;);</span><br><span class="line">                            ctx.writeAndFlush(buffer);</span><br><span class="line">                            <span class="comment">// 发完即关</span></span><br><span class="line">                            ctx.close();</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            <span class="type">ChannelFuture</span> <span class="variable">channelFuture</span> <span class="operator">=</span> bootstrap.connect(<span class="string">&quot;localhost&quot;</span>, <span class="number">8080</span>).sync();</span><br><span class="line">            channelFuture.channel().closeFuture().sync();</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            log.error(<span class="string">&quot;client error&quot;</span>, e);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            worker.shutdownGracefully();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>半包用这种办法还是不好解决，因为接收方的缓冲区大小是有限的</p>
</blockquote>
<h4 id="方法2，固定长度"><a href="#方法2，固定长度" class="headerlink" title="方法2，固定长度"></a>方法2，固定长度</h4><p>让所有数据包长度固定（假设长度为 8 字节），服务器端加入</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">FixedLengthFrameDecoder</span>(<span class="number">8</span>));</span><br></pre></td></tr></table></figure>

<p>缺点是，数据包的大小不好把握</p>
<ul>
<li>长度定的太大，浪费</li>
<li>长度定的太小，对某些数据包又显得不够</li>
</ul>
<h4 id="方法3，固定分隔符"><a href="#方法3，固定分隔符" class="headerlink" title="方法3，固定分隔符"></a>方法3，固定分隔符</h4><p>服务端加入，默认以 \n 或 \r\n 作为分隔符，如果超出指定长度仍未出现分隔符，则抛出异常</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">LineBasedFrameDecoder</span>(<span class="number">1024</span>));</span><br></pre></td></tr></table></figure>

<p>缺点，处理字符数据比较合适，但如果内容本身包含了分隔符（字节数据常常会有此情况），那么就会解析错误</p>
<h4 id="方法4，预设长度"><a href="#方法4，预设长度" class="headerlink" title="方法4，预设长度"></a>方法4，预设长度</h4><p>在发送消息前，先约定用定长字节表示接下来数据的长度</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 最大长度，长度偏移，长度占用字节，长度调整，剥离字节数</span></span><br><span class="line">ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">LengthFieldBasedFrameDecoder</span>(<span class="number">1024</span>, <span class="number">0</span>, <span class="number">4</span>, <span class="number">0</span>, <span class="number">4</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">//客户端，先写入长度，再写入内容</span></span><br><span class="line"><span class="type">int</span> <span class="variable">length</span> <span class="operator">=</span> bytes.length;</span><br><span class="line">buffer.writeInt(length);</span><br><span class="line">buffer.writeBytes(bytes);</span><br></pre></td></tr></table></figure>

<p>长度调整就是长度后面的内容，比如加一个版本号</p>
<h2 id="2-协议设计与解析"><a href="#2-协议设计与解析" class="headerlink" title="2. 协议设计与解析"></a>2. 协议设计与解析</h2><p>TCP/IP 中消息传输基于流的方式，没有边界。</p>
<p>协议的目的就是划定消息的边界，制定通信双方要共同遵守的通信规则</p>
<h3 id="2-1-redis-协议举例"><a href="#2-1-redis-协议举例" class="headerlink" title="2.1 redis 协议举例"></a>2.1 redis 协议举例</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">NioEventLoopGroup</span> <span class="variable">worker</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line"><span class="type">byte</span>[] LINE = &#123;<span class="number">13</span>, <span class="number">10</span>&#125;;<span class="comment">//回车和换行</span></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="type">Bootstrap</span> <span class="variable">bootstrap</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>();</span><br><span class="line">    bootstrap.channel(NioSocketChannel.class);</span><br><span class="line">    bootstrap.group(worker);</span><br><span class="line">    bootstrap.handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;SocketChannel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(SocketChannel ch)</span> &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">LoggingHandler</span>());</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">ChannelInboundHandlerAdapter</span>() &#123;</span><br><span class="line">                <span class="comment">// 会在连接 channel 建立成功后，会触发 active 事件</span></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> &#123;</span><br><span class="line">                    <span class="type">ByteBuf</span> <span class="variable">buf</span> <span class="operator">=</span> ctx.alloc().buffer();</span><br><span class="line">                    buf.writeBytes(<span class="string">&quot;*3&quot;</span>.getBytes());</span><br><span class="line">                    buf.writeBytes(LINE);</span><br><span class="line">                    buf.writeBytes(<span class="string">&quot;$3&quot;</span>.getBytes());</span><br><span class="line">                    buf.writeBytes(LINE);</span><br><span class="line">                    buf.writeBytes(<span class="string">&quot;set&quot;</span>.getBytes());</span><br><span class="line">                    buf.writeBytes(LINE);</span><br><span class="line">                    buf.writeBytes(<span class="string">&quot;$3&quot;</span>.getBytes());</span><br><span class="line">                    buf.writeBytes(LINE);</span><br><span class="line">                    buf.writeBytes(<span class="string">&quot;aaa&quot;</span>.getBytes());</span><br><span class="line">                    buf.writeBytes(LINE);</span><br><span class="line">                    buf.writeBytes(<span class="string">&quot;$3&quot;</span>.getBytes());</span><br><span class="line">                    buf.writeBytes(LINE);</span><br><span class="line">                    buf.writeBytes(<span class="string">&quot;bbb&quot;</span>.getBytes());</span><br><span class="line">                    buf.writeBytes(LINE);</span><br><span class="line">                    ctx.writeAndFlush(buf);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                    <span class="type">ByteBuf</span> <span class="variable">buf</span> <span class="operator">=</span> (ByteBuf) msg;</span><br><span class="line">                    System.out.println(buf.toString(Charset.defaultCharset()));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="type">ChannelFuture</span> <span class="variable">channelFuture</span> <span class="operator">=</span> bootstrap.connect(<span class="string">&quot;localhost&quot;</span>, <span class="number">6379</span>).sync();<span class="comment">//连接redis</span></span><br><span class="line">    channelFuture.channel().closeFuture().sync();</span><br><span class="line">&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">    log.error(<span class="string">&quot;client error&quot;</span>, e);</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    worker.shutdownGracefully();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>比如set aaa bbb，redis约定的协议为：数组长度  命令的长度 key的长度 key内容 value长度 value内容</p>
<h3 id="2-2-http-协议举例"><a href="#2-2-http-协议举例" class="headerlink" title="2.2 http 协议举例"></a>2.2 http 协议举例</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">NioEventLoopGroup</span> <span class="variable">boss</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line"><span class="type">NioEventLoopGroup</span> <span class="variable">worker</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="type">ServerBootstrap</span> <span class="variable">serverBootstrap</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ServerBootstrap</span>();</span><br><span class="line">    serverBootstrap.channel(NioServerSocketChannel.class);</span><br><span class="line">    serverBootstrap.group(boss, worker);</span><br><span class="line">    serverBootstrap.childHandler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;SocketChannel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(SocketChannel ch)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">LoggingHandler</span>(LogLevel.DEBUG));</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">HttpServerCodec</span>());</span><br><span class="line">            ch.pipeline().addLast(<span class="keyword">new</span> <span class="title class_">SimpleChannelInboundHandler</span>&lt;HttpRequest&gt;() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, HttpRequest msg)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                    <span class="comment">// 获取请求</span></span><br><span class="line">                    log.debug(msg.uri());</span><br><span class="line">                    <span class="comment">// 返回响应</span></span><br><span class="line">                    <span class="type">DefaultFullHttpResponse</span> <span class="variable">response</span> <span class="operator">=</span></span><br><span class="line">                            <span class="keyword">new</span> <span class="title class_">DefaultFullHttpResponse</span>(msg.protocolVersion(), HttpResponseStatus.OK);</span><br><span class="line"></span><br><span class="line">                    <span class="type">byte</span>[] bytes = <span class="string">&quot;&lt;h1&gt;Hello, world!&lt;/h1&gt;&quot;</span>.getBytes();</span><br><span class="line"></span><br><span class="line">                    response.headers().setInt(CONTENT_LENGTH, bytes.length);</span><br><span class="line">                    response.content().writeBytes(bytes);</span><br><span class="line"></span><br><span class="line">                    <span class="comment">// 写回响应</span></span><br><span class="line">                    ctx.writeAndFlush(response);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="type">ChannelFuture</span> <span class="variable">channelFuture</span> <span class="operator">=</span> serverBootstrap.bind(<span class="number">8080</span>).sync();</span><br><span class="line">    channelFuture.channel().closeFuture().sync();</span><br><span class="line">&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">    log.error(<span class="string">&quot;server error&quot;</span>, e);</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    boss.shutdownGracefully();</span><br><span class="line">    worker.shutdownGracefully();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-3-自定义协议要素"><a href="#2-3-自定义协议要素" class="headerlink" title="2.3 自定义协议要素"></a>2.3 自定义协议要素</h3><ul>
<li>魔数，用来在第一时间判定是否是无效数据包</li>
<li>版本号，可以支持协议的升级</li>
<li>序列化算法，消息正文到底采用哪种序列化反序列化方式，可以由此扩展，例如：json、protobuf、hessian、jdk</li>
<li>指令类型，是登录、注册、单聊、群聊… 跟业务相关</li>
<li>请求序号，为了双工通信，提供异步能力</li>
<li>正文长度</li>
<li>消息正文</li>
</ul>
<h4 id="编解码器"><a href="#编解码器" class="headerlink" title="编解码器"></a>编解码器</h4><p>根据上面的要素，设计一个登录请求消息和登录响应消息，并使用 Netty 完成收发</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MessageCodec</span> <span class="keyword">extends</span> <span class="title class_">ByteToMessageCodec</span>&lt;Message&gt; &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">encode</span><span class="params">(ChannelHandlerContext ctx, Message msg, ByteBuf out)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 1. 4 字节的魔数</span></span><br><span class="line">        out.writeBytes(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;);</span><br><span class="line">        <span class="comment">// 2. 1 字节的版本,</span></span><br><span class="line">        out.writeByte(<span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 3. 1 字节的序列化方式 jdk 0 , json 1</span></span><br><span class="line">        out.writeByte(<span class="number">0</span>);</span><br><span class="line">        <span class="comment">// 4. 1 字节的指令类型</span></span><br><span class="line">        out.writeByte(msg.getMessageType());</span><br><span class="line">        <span class="comment">// 5. 4 个字节</span></span><br><span class="line">        out.writeInt(msg.getSequenceId());</span><br><span class="line">        <span class="comment">// 无意义，对齐填充，让字节数满足2的n次方</span></span><br><span class="line">        out.writeByte(<span class="number">0xff</span>);</span><br><span class="line">        <span class="comment">// 6. 获取内容的字节数组</span></span><br><span class="line">        <span class="type">ByteArrayOutputStream</span> <span class="variable">bos</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ByteArrayOutputStream</span>();</span><br><span class="line">        <span class="type">ObjectOutputStream</span> <span class="variable">oos</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectOutputStream</span>(bos);</span><br><span class="line">        oos.writeObject(msg);<span class="comment">//这里是直接序列化了，也可以通过json转为字节数组</span></span><br><span class="line">        <span class="type">byte</span>[] bytes = bos.toByteArray();</span><br><span class="line">        <span class="comment">// 7. 长度</span></span><br><span class="line">        out.writeInt(bytes.length);</span><br><span class="line">        <span class="comment">// 8. 写入内容</span></span><br><span class="line">        out.writeBytes(bytes);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">decode</span><span class="params">(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">magicNum</span> <span class="operator">=</span> in.readInt();</span><br><span class="line">        <span class="type">byte</span> <span class="variable">version</span> <span class="operator">=</span> in.readByte();</span><br><span class="line">        <span class="type">byte</span> <span class="variable">serializerType</span> <span class="operator">=</span> in.readByte();</span><br><span class="line">        <span class="type">byte</span> <span class="variable">messageType</span> <span class="operator">=</span> in.readByte();</span><br><span class="line">        <span class="type">int</span> <span class="variable">sequenceId</span> <span class="operator">=</span> in.readInt();</span><br><span class="line">        in.readByte();</span><br><span class="line">        <span class="type">int</span> <span class="variable">length</span> <span class="operator">=</span> in.readInt();</span><br><span class="line">        <span class="type">byte</span>[] bytes = <span class="keyword">new</span> <span class="title class_">byte</span>[length];</span><br><span class="line">        in.readBytes(bytes, <span class="number">0</span>, length);</span><br><span class="line">        <span class="type">ObjectInputStream</span> <span class="variable">ois</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectInputStream</span>(<span class="keyword">new</span> <span class="title class_">ByteArrayInputStream</span>(bytes));</span><br><span class="line">        <span class="type">Message</span> <span class="variable">message</span> <span class="operator">=</span> (Message) ois.readObject();</span><br><span class="line">        log.debug(<span class="string">&quot;&#123;&#125;, &#123;&#125;, &#123;&#125;, &#123;&#125;, &#123;&#125;, &#123;&#125;&quot;</span>, magicNum, version, serializerType, messageType, sequenceId, length);</span><br><span class="line">        log.debug(<span class="string">&quot;&#123;&#125;&quot;</span>, message);</span><br><span class="line">        out.add(message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>测试</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">EmbeddedChannel</span> <span class="variable">channel</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">EmbeddedChannel</span>(</span><br><span class="line">    <span class="keyword">new</span> <span class="title class_">LoggingHandler</span>(),</span><br><span class="line">    <span class="keyword">new</span> <span class="title class_">LengthFieldBasedFrameDecoder</span>(</span><br><span class="line">        <span class="number">1024</span>, <span class="number">12</span>, <span class="number">4</span>, <span class="number">0</span>, <span class="number">0</span>),</span><br><span class="line">    <span class="keyword">new</span> <span class="title class_">MessageCodec</span>()</span><br><span class="line">);</span><br><span class="line"><span class="comment">// encode</span></span><br><span class="line"><span class="type">LoginRequestMessage</span> <span class="variable">message</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">LoginRequestMessage</span>(<span class="string">&quot;zhangsan&quot;</span>, <span class="string">&quot;123&quot;</span>, <span class="string">&quot;张三&quot;</span>);</span><br><span class="line"><span class="comment">//        channel.writeOutbound(message);</span></span><br><span class="line"><span class="comment">// decode</span></span><br><span class="line"><span class="type">ByteBuf</span> <span class="variable">buf</span> <span class="operator">=</span> ByteBufAllocator.DEFAULT.buffer();</span><br><span class="line"><span class="keyword">new</span> <span class="title class_">MessageCodec</span>().encode(<span class="literal">null</span>, message, buf);</span><br><span class="line">channel.writeInbound(buf);</span><br></pre></td></tr></table></figure>

<p>解读</p>
<p><img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0013.png"></p>
<h4 id="什么时候可以加-Sharable"><a href="#什么时候可以加-Sharable" class="headerlink" title="什么时候可以加 @Sharable"></a>什么时候可以加 @Sharable</h4><ul>
<li>当 handler 不保存状态时，就可以安全地在多线程下被共享</li>
<li>可以共享的handler会有注解@Sharable</li>
</ul>
<p>对于上述自定义的handler</p>
<ul>
<li>不能继承 ByteToMessageCodec 或 CombinedChannelDuplexHandler 父类，他们的构造方法对 @Sharable 有限制</li>
<li>如果能确保编解码器不会保存状态，可以继承 MessageToMessageCodec 父类</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@ChannelHandler</span>.Sharable</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 必须和 LengthFieldBasedFrameDecoder 一起使用，确保接到的 ByteBuf 消息是完整的</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MessageCodecSharable</span> <span class="keyword">extends</span> <span class="title class_">MessageToMessageCodec</span>&lt;ByteBuf, Message&gt; &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">encode</span><span class="params">(ChannelHandlerContext ctx, Message msg, List&lt;Object&gt; outList)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">ByteBuf</span> <span class="variable">out</span> <span class="operator">=</span> ctx.alloc().buffer();</span><br><span class="line">        <span class="comment">// 1. 4 字节的魔数</span></span><br><span class="line">        out.writeBytes(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;);</span><br><span class="line">        <span class="comment">// 2. 1 字节的版本,</span></span><br><span class="line">        out.writeByte(<span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 3. 1 字节的序列化方式 jdk 0 , json 1</span></span><br><span class="line">        out.writeByte(<span class="number">0</span>);</span><br><span class="line">        <span class="comment">// 4. 1 字节的指令类型</span></span><br><span class="line">        out.writeByte(msg.getMessageType());</span><br><span class="line">        <span class="comment">// 5. 4 个字节</span></span><br><span class="line">        out.writeInt(msg.getSequenceId());</span><br><span class="line">        <span class="comment">// 无意义，对齐填充</span></span><br><span class="line">        out.writeByte(<span class="number">0xff</span>);</span><br><span class="line">        <span class="comment">// 6. 获取内容的字节数组</span></span><br><span class="line">        <span class="type">ByteArrayOutputStream</span> <span class="variable">bos</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ByteArrayOutputStream</span>();</span><br><span class="line">        <span class="type">ObjectOutputStream</span> <span class="variable">oos</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectOutputStream</span>(bos);</span><br><span class="line">        oos.writeObject(msg);</span><br><span class="line">        <span class="type">byte</span>[] bytes = bos.toByteArray();</span><br><span class="line">        <span class="comment">// 7. 长度</span></span><br><span class="line">        out.writeInt(bytes.length);</span><br><span class="line">        <span class="comment">// 8. 写入内容</span></span><br><span class="line">        out.writeBytes(bytes);</span><br><span class="line">        outList.add(out);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">decode</span><span class="params">(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">magicNum</span> <span class="operator">=</span> in.readInt();</span><br><span class="line">        <span class="type">byte</span> <span class="variable">version</span> <span class="operator">=</span> in.readByte();</span><br><span class="line">        <span class="type">byte</span> <span class="variable">serializerType</span> <span class="operator">=</span> in.readByte();</span><br><span class="line">        <span class="type">byte</span> <span class="variable">messageType</span> <span class="operator">=</span> in.readByte();</span><br><span class="line">        <span class="type">int</span> <span class="variable">sequenceId</span> <span class="operator">=</span> in.readInt();</span><br><span class="line">        in.readByte();</span><br><span class="line">        <span class="type">int</span> <span class="variable">length</span> <span class="operator">=</span> in.readInt();</span><br><span class="line">        <span class="type">byte</span>[] bytes = <span class="keyword">new</span> <span class="title class_">byte</span>[length];</span><br><span class="line">        in.readBytes(bytes, <span class="number">0</span>, length);</span><br><span class="line">        <span class="type">ObjectInputStream</span> <span class="variable">ois</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectInputStream</span>(<span class="keyword">new</span> <span class="title class_">ByteArrayInputStream</span>(bytes));</span><br><span class="line">        <span class="type">Message</span> <span class="variable">message</span> <span class="operator">=</span> (Message) ois.readObject();</span><br><span class="line">        log.debug(<span class="string">&quot;&#123;&#125;, &#123;&#125;, &#123;&#125;, &#123;&#125;, &#123;&#125;, &#123;&#125;&quot;</span>, magicNum, version, serializerType, messageType, sequenceId, length);</span><br><span class="line">        log.debug(<span class="string">&quot;&#123;&#125;&quot;</span>, message);</span><br><span class="line">        out.add(message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="优化"><a href="#优化" class="headerlink" title="优化"></a>优化</h1><h2 id="1-1-扩展序列化算法"><a href="#1-1-扩展序列化算法" class="headerlink" title="1.1 扩展序列化算法"></a>1.1 扩展序列化算法</h2><p>序列化，反序列化主要用在消息正文的转换上</p>
<ul>
<li>序列化时，需要将 Java 对象变为要传输的数据（可以是 byte[]，或 json 等，最终都需要变成 byte[]）</li>
<li>反序列化时，需要将传入的正文数据还原成 Java 对象，便于处理</li>
</ul>
<p>之前写的netty聊天室代码仅支持 Java 自带的序列化，反序列化机制，核心代码如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 反序列化</span></span><br><span class="line"><span class="type">byte</span>[] bytes = <span class="keyword">new</span> <span class="title class_">byte</span>[length];</span><br><span class="line">in.readBytes(bytes, <span class="number">0</span>, length);</span><br><span class="line"><span class="type">ObjectInputStream</span> <span class="variable">ois</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectInputStream</span>(<span class="keyword">new</span> <span class="title class_">ByteArrayInputStream</span>(bytes));</span><br><span class="line"><span class="type">Message</span> <span class="variable">message</span> <span class="operator">=</span> (Message) ois.readObject();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 序列化</span></span><br><span class="line"><span class="type">ByteArrayOutputStream</span> <span class="variable">bos</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ByteArrayOutputStream</span>();</span><br><span class="line"><span class="type">ObjectOutputStream</span> <span class="variable">oos</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectOutputStream</span>(bos);</span><br><span class="line">oos.writeObject(msg);</span><br><span class="line"><span class="type">byte</span>[] bytes = bos.toByteArray();</span><br></pre></td></tr></table></figure>

<p>为了支持更多序列化算法，抽象一个 Serializer 接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Serializer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 反序列化方法</span></span><br><span class="line">    &lt;T&gt; T <span class="title function_">deserialize</span><span class="params">(Class&lt;T&gt; clazz, <span class="type">byte</span>[] bytes)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 序列化方法</span></span><br><span class="line">    &lt;T&gt; <span class="type">byte</span>[] serialize(T object);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>提供两个实现，这里直接将实现加入了枚举类 SerializerAlgorithm 中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">enum</span> <span class="title class_">SerializerAlgorithm</span> <span class="keyword">implements</span> <span class="title class_">Serializer</span> &#123;</span><br><span class="line">	<span class="comment">// Java 实现</span></span><br><span class="line">    Java &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">public</span> &lt;T&gt; T <span class="title function_">deserialize</span><span class="params">(Class&lt;T&gt; clazz, <span class="type">byte</span>[] bytes)</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="type">ObjectInputStream</span> <span class="variable">in</span> <span class="operator">=</span> </span><br><span class="line">                    <span class="keyword">new</span> <span class="title class_">ObjectInputStream</span>(<span class="keyword">new</span> <span class="title class_">ByteArrayInputStream</span>(bytes));</span><br><span class="line">                <span class="keyword">return</span> (T) in.readObject();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException | ClassNotFoundException e) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;SerializerAlgorithm.Java 反序列化错误&quot;</span>, e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">public</span> &lt;T&gt; <span class="type">byte</span>[] serialize(T object) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="type">ByteArrayOutputStream</span> <span class="variable">out</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ByteArrayOutputStream</span>();</span><br><span class="line">                <span class="keyword">new</span> <span class="title class_">ObjectOutputStream</span>(out).writeObject(object);</span><br><span class="line">                <span class="keyword">return</span> out.toByteArray();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;SerializerAlgorithm.Java 序列化错误&quot;</span>, e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, </span><br><span class="line">    <span class="comment">// Json 实现(引入了 Gson 依赖)</span></span><br><span class="line">    Json &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">public</span> &lt;T&gt; T <span class="title function_">deserialize</span><span class="params">(Class&lt;T&gt; clazz, <span class="type">byte</span>[] bytes)</span> &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">json</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(bytes, StandardCharsets.UTF_8);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Gson</span>().fromJson(json, clazz);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">public</span> &lt;T&gt; <span class="type">byte</span>[] serialize(T object) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">json</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Gson</span>().toJson(object);</span><br><span class="line">            <span class="keyword">return</span> json.getBytes(StandardCharsets.UTF_8);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>在编码时，一般通过配置类决定用哪种序列化方法，而解码时是从ByteBuf里面读取用的哪种序列化方式以及解码为哪种类，从而避免了SerializerAlgorithm.java这种写死的方式</strong></p>
<p>增加配置类和配置文件</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">Config</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> Properties properties;</span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> (<span class="type">InputStream</span> <span class="variable">in</span> <span class="operator">=</span> Config.class.getResourceAsStream(<span class="string">&quot;/application.properties&quot;</span>)) &#123;</span><br><span class="line">            properties = <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">            properties.load(in);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">ExceptionInInitializerError</span>(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="type">int</span> <span class="title function_">getServerPort</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">value</span> <span class="operator">=</span> properties.getProperty(<span class="string">&quot;server.port&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span>(value == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="number">8080</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> Integer.parseInt(value);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Serializer.Algorithm <span class="title function_">getSerializerAlgorithm</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">value</span> <span class="operator">=</span> properties.getProperty(<span class="string">&quot;serializer.algorithm&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span>(value == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> Serializer.Algorithm.Java;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> Serializer.Algorithm.valueOf(value);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>配置文件</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">serializer.algorithm</span>=<span class="string">Json</span></span><br></pre></td></tr></table></figure>

<p>修改编解码器</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MessageCodecSharable</span> <span class="keyword">extends</span> <span class="title class_">MessageToMessageCodec</span>&lt;ByteBuf, Message&gt; &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">encode</span><span class="params">(ChannelHandlerContext ctx, Message msg, List&lt;Object&gt; outList)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">ByteBuf</span> <span class="variable">out</span> <span class="operator">=</span> ctx.alloc().buffer();</span><br><span class="line">        <span class="comment">// 1. 4 字节的魔数</span></span><br><span class="line">        out.writeBytes(<span class="keyword">new</span> <span class="title class_">byte</span>[]&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;);</span><br><span class="line">        <span class="comment">// 2. 1 字节的版本,</span></span><br><span class="line">        out.writeByte(<span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 3. 1 字节的序列化方式 jdk 0 , json 1</span></span><br><span class="line">        out.writeByte(Config.getSerializerAlgorithm().ordinal());<span class="comment">//枚举对象会有顺序，java就是0</span></span><br><span class="line">        <span class="comment">// 4. 1 字节的指令类型</span></span><br><span class="line">        out.writeByte(msg.getMessageType());</span><br><span class="line">        <span class="comment">// 5. 4 个字节</span></span><br><span class="line">        out.writeInt(msg.getSequenceId());</span><br><span class="line">        <span class="comment">// 无意义，对齐填充</span></span><br><span class="line">        out.writeByte(<span class="number">0xff</span>);</span><br><span class="line">        <span class="comment">// 6. 获取内容的字节数组</span></span><br><span class="line">        <span class="type">byte</span>[] bytes = Config.getSerializerAlgorithm().serialize(msg);</span><br><span class="line">        <span class="comment">// 7. 长度</span></span><br><span class="line">        out.writeInt(bytes.length);</span><br><span class="line">        <span class="comment">// 8. 写入内容</span></span><br><span class="line">        out.writeBytes(bytes);</span><br><span class="line">        outList.add(out);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">decode</span><span class="params">(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">magicNum</span> <span class="operator">=</span> in.readInt();</span><br><span class="line">        <span class="type">byte</span> <span class="variable">version</span> <span class="operator">=</span> in.readByte();</span><br><span class="line">        <span class="type">byte</span> <span class="variable">serializerAlgorithm</span> <span class="operator">=</span> in.readByte(); <span class="comment">// 0 或 1</span></span><br><span class="line">        <span class="type">byte</span> <span class="variable">messageType</span> <span class="operator">=</span> in.readByte(); <span class="comment">// 0,1,2...</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">sequenceId</span> <span class="operator">=</span> in.readInt();</span><br><span class="line">        in.readByte();</span><br><span class="line">        <span class="type">int</span> <span class="variable">length</span> <span class="operator">=</span> in.readInt();</span><br><span class="line">        <span class="type">byte</span>[] bytes = <span class="keyword">new</span> <span class="title class_">byte</span>[length];</span><br><span class="line">        in.readBytes(bytes, <span class="number">0</span>, length);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 找到反序列化算法</span></span><br><span class="line">        Serializer.<span class="type">Algorithm</span> <span class="variable">algorithm</span> <span class="operator">=</span> Serializer.Algorithm.values()[serializerAlgorithm];</span><br><span class="line">        <span class="comment">// 确定具体消息类型</span></span><br><span class="line">        Class&lt;? <span class="keyword">extends</span> <span class="title class_">Message</span>&gt; messageClass = Message.getMessageClass(messageType);</span><br><span class="line">        <span class="type">Message</span> <span class="variable">message</span> <span class="operator">=</span> algorithm.deserialize(messageClass, bytes);</span><br><span class="line">        out.add(message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中确定具体消息类型，可以根据 <code>消息类型字节</code> 获取到对应的 <code>消息 class</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">Message</span> <span class="keyword">implements</span> <span class="title class_">Serializable</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据消息类型字节，获得对应的消息 class</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> messageType 消息类型字节</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 消息 class</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Class&lt;? <span class="keyword">extends</span> <span class="title class_">Message</span>&gt; getMessageClass(<span class="type">int</span> messageType) &#123;</span><br><span class="line">        <span class="keyword">return</span> messageClasses.get(messageType);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> sequenceId;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> messageType;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="type">int</span> <span class="title function_">getMessageType</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">LoginRequestMessage</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">LoginResponseMessage</span> <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">ChatRequestMessage</span> <span class="operator">=</span> <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">ChatResponseMessage</span> <span class="operator">=</span> <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">GroupCreateRequestMessage</span> <span class="operator">=</span> <span class="number">4</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">GroupCreateResponseMessage</span> <span class="operator">=</span> <span class="number">5</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">GroupJoinRequestMessage</span> <span class="operator">=</span> <span class="number">6</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">GroupJoinResponseMessage</span> <span class="operator">=</span> <span class="number">7</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">GroupQuitRequestMessage</span> <span class="operator">=</span> <span class="number">8</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">GroupQuitResponseMessage</span> <span class="operator">=</span> <span class="number">9</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">GroupChatRequestMessage</span> <span class="operator">=</span> <span class="number">10</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">GroupChatResponseMessage</span> <span class="operator">=</span> <span class="number">11</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">GroupMembersRequestMessage</span> <span class="operator">=</span> <span class="number">12</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">GroupMembersResponseMessage</span> <span class="operator">=</span> <span class="number">13</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">PingMessage</span> <span class="operator">=</span> <span class="number">14</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">PongMessage</span> <span class="operator">=</span> <span class="number">15</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Map&lt;Integer, Class&lt;? <span class="keyword">extends</span> <span class="title class_">Message</span>&gt;&gt; messageClasses = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        messageClasses.put(LoginRequestMessage, LoginRequestMessage.class);</span><br><span class="line">        messageClasses.put(LoginResponseMessage, LoginResponseMessage.class);</span><br><span class="line">        messageClasses.put(ChatRequestMessage, ChatRequestMessage.class);</span><br><span class="line">        messageClasses.put(ChatResponseMessage, ChatResponseMessage.class);</span><br><span class="line">        messageClasses.put(GroupCreateRequestMessage, GroupCreateRequestMessage.class);</span><br><span class="line">        messageClasses.put(GroupCreateResponseMessage, GroupCreateResponseMessage.class);</span><br><span class="line">        messageClasses.put(GroupJoinRequestMessage, GroupJoinRequestMessage.class);</span><br><span class="line">        messageClasses.put(GroupJoinResponseMessage, GroupJoinResponseMessage.class);</span><br><span class="line">        messageClasses.put(GroupQuitRequestMessage, GroupQuitRequestMessage.class);</span><br><span class="line">        messageClasses.put(GroupQuitResponseMessage, GroupQuitResponseMessage.class);</span><br><span class="line">        messageClasses.put(GroupChatRequestMessage, GroupChatRequestMessage.class);</span><br><span class="line">        messageClasses.put(GroupChatResponseMessage, GroupChatResponseMessage.class);</span><br><span class="line">        messageClasses.put(GroupMembersRequestMessage, GroupMembersRequestMessage.class);</span><br><span class="line">        messageClasses.put(GroupMembersResponseMessage, GroupMembersResponseMessage.class);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="1-2-参数调优"><a href="#1-2-参数调优" class="headerlink" title="1.2 参数调优"></a>1.2 参数调优</h2><h4 id="1）CONNECT-TIMEOUT-MILLIS"><a href="#1）CONNECT-TIMEOUT-MILLIS" class="headerlink" title="1）CONNECT_TIMEOUT_MILLIS"></a>1）CONNECT_TIMEOUT_MILLIS</h4><ul>
<li><p>属于 SocketChannal 参数</p>
</li>
<li><p>用在客户端建立连接时，如果在指定毫秒内无法连接，会抛出 timeout 异常</p>
</li>
<li><p>SO_TIMEOUT 主要用在阻塞 IO，阻塞 IO 中 accept，read 等都是无限等待的，如果不希望永远阻塞，使用它调整超时时间</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestConnectionTimeout</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">NioEventLoopGroup</span> <span class="variable">group</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">Bootstrap</span> <span class="variable">bootstrap</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>()</span><br><span class="line">                    .group(group)</span><br><span class="line">                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, <span class="number">300</span>)</span><br><span class="line">                    .channel(NioSocketChannel.class)</span><br><span class="line">                    .handler(<span class="keyword">new</span> <span class="title class_">LoggingHandler</span>());</span><br><span class="line">            <span class="type">ChannelFuture</span> <span class="variable">future</span> <span class="operator">=</span> bootstrap.connect(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8080</span>);</span><br><span class="line">            future.sync().channel().closeFuture().sync(); <span class="comment">// 断点1</span></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            log.debug(<span class="string">&quot;timeout&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            group.shutdownGracefully();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>另外源码部分 <code>io.netty.channel.nio.AbstractNioChannel.AbstractNioUnsafe#connect</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">connect</span><span class="params">(</span></span><br><span class="line"><span class="params">        <span class="keyword">final</span> SocketAddress remoteAddress, <span class="keyword">final</span> SocketAddress localAddress, <span class="keyword">final</span> ChannelPromise promise)</span> &#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">    <span class="comment">// Schedule connect timeout.</span></span><br><span class="line">    <span class="type">int</span> <span class="variable">connectTimeoutMillis</span> <span class="operator">=</span> config().getConnectTimeoutMillis();</span><br><span class="line">    <span class="keyword">if</span> (connectTimeoutMillis &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        connectTimeoutFuture = eventLoop().schedule(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;                </span><br><span class="line">                <span class="type">ChannelPromise</span> <span class="variable">connectPromise</span> <span class="operator">=</span> AbstractNioChannel.<span class="built_in">this</span>.connectPromise;</span><br><span class="line">                <span class="type">ConnectTimeoutException</span> <span class="variable">cause</span> <span class="operator">=</span></span><br><span class="line">                    <span class="keyword">new</span> <span class="title class_">ConnectTimeoutException</span>(<span class="string">&quot;connection timed out: &quot;</span> + remoteAddress); <span class="comment">// 断点2</span></span><br><span class="line">                <span class="keyword">if</span> (connectPromise != <span class="literal">null</span> &amp;&amp; connectPromise.tryFailure(cause)) &#123;</span><br><span class="line">                    close(voidPromise());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, connectTimeoutMillis, TimeUnit.MILLISECONDS);</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>所以连接超时就是一个定时任务，抛出异常，连接成功会把任务给取消掉</p>
<h4 id="2）SO-BACKLOG"><a href="#2）SO-BACKLOG" class="headerlink" title="2）SO_BACKLOG"></a>2）SO_BACKLOG</h4><ul>
<li>属于 ServerSocketChannal 参数</li>
</ul>
<p>三次握手的流程</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">sequenceDiagram</span><br><span class="line"></span><br><span class="line">participant c as client</span><br><span class="line">participant s as server</span><br><span class="line">participant sq as syns queue</span><br><span class="line">participant aq as accept queue</span><br><span class="line"></span><br><span class="line">s -&gt;&gt; s : bind()</span><br><span class="line">s -&gt;&gt; s : listen()</span><br><span class="line">c -&gt;&gt; c : connect()</span><br><span class="line">c -&gt;&gt; s : 1. SYN</span><br><span class="line">Note left of c : SYN_SEND</span><br><span class="line">s -&gt;&gt; sq : put</span><br><span class="line">Note right of s : SYN_RCVD</span><br><span class="line">s -&gt;&gt; c : 2. SYN + ACK</span><br><span class="line">Note left of c : ESTABLISHED</span><br><span class="line">c -&gt;&gt; s : 3. ACK</span><br><span class="line">sq -&gt;&gt; aq : put</span><br><span class="line">Note right of s : ESTABLISHED</span><br><span class="line">aq --&gt;&gt; s : </span><br><span class="line">s -&gt;&gt; s : accept()</span><br></pre></td></tr></table></figure>

<ol>
<li>第一次握手，client 发送 SYN 到 server，状态修改为 SYN_SEND，server 收到，状态改变为 SYN_REVD，并将该请求放入 sync queue 队列（半连接队列）</li>
<li>第二次握手，server 回复 SYN + ACK 给 client，client 收到，状态改变为 ESTABLISHED，并发送 ACK 给 server</li>
<li>第三次握手，server 收到 ACK，状态改变为 ESTABLISHED，将该请求从 sync queue 放入 accept queue</li>
</ol>
<p>其中</p>
<ul>
<li><p>在 linux 2.2 之前，backlog 大小包括了两个队列的大小，在 2.2 之后，分别用下面两个参数来控制</p>
</li>
<li><p>sync queue - 半连接队列</p>
<ul>
<li>大小通过 /proc/sys/net/ipv4/tcp_max_syn_backlog 指定，在 <code>syncookies</code> 启用的情况下，逻辑上没有最大值限制，这个设置便被忽略</li>
</ul>
</li>
<li><p>accept queue - 全连接队列</p>
<ul>
<li>其大小通过 /proc/sys/net/core/somaxconn 指定，在使用 listen 函数时，内核会根据传入的 backlog 参数与系统参数，取二者的较小值</li>
<li>如果 accpet queue 队列满了，server 将发送一个拒绝连接的错误信息到 client</li>
</ul>
</li>
</ul>
<p>netty 中可以通过  option(ChannelOption.SO_BACKLOG, 值) 来设置大小</p>
<p>可以通过下面源码查看默认大小</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//通过find Usages功能查看bind方法在哪被调用了</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> ServerSocketChannel <span class="title function_">bind</span><span class="params">(SocketAddress local, <span class="type">int</span> backlog)</span></span><br><span class="line"><span class="comment">//找到源码</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DefaultServerSocketChannelConfig</span> <span class="keyword">extends</span> <span class="title class_">DefaultChannelConfig</span></span><br><span class="line">                                              <span class="keyword">implements</span> <span class="title class_">ServerSocketChannelConfig</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="type">int</span> <span class="variable">backlog</span> <span class="operator">=</span> NetUtil.SOMAXCONN;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3）ulimit-n"><a href="#3）ulimit-n" class="headerlink" title="3）ulimit -n"></a>3）ulimit -n</h4><ul>
<li>属于操作系统参数，限制一个进程可以同时打开的文件描述符的上限</li>
</ul>
<h4 id="4）TCP-NODELAY"><a href="#4）TCP-NODELAY" class="headerlink" title="4）TCP_NODELAY"></a>4）TCP_NODELAY</h4><ul>
<li>属于 SocketChannal 参数 默认为false开启nagle算法，一般设为true避免延迟</li>
</ul>
<h4 id="5）SO-SNDBUF-amp-SO-RCVBUF"><a href="#5）SO-SNDBUF-amp-SO-RCVBUF" class="headerlink" title="5）SO_SNDBUF &amp; SO_RCVBUF"></a>5）SO_SNDBUF &amp; SO_RCVBUF</h4><ul>
<li>SO_SNDBUF 发送缓冲区，属于 SocketChannal 参数</li>
<li>SO_RCVBUF 接受缓冲区，既可用于 SocketChannal 参数，也可以用于 ServerSocketChannal 参数（建议设置到 ServerSocketChannal 上）</li>
</ul>
<h4 id="6）ALLOCATOR"><a href="#6）ALLOCATOR" class="headerlink" title="6）ALLOCATOR"></a>6）ALLOCATOR</h4><ul>
<li>属于 SocketChannal 参数</li>
<li>用来分配 ByteBuf是否池化，是否使用直接内存， ctx.alloc()</li>
</ul>
<h4 id="7）RCVBUF-ALLOCATOR"><a href="#7）RCVBUF-ALLOCATOR" class="headerlink" title="7）RCVBUF_ALLOCATOR"></a>7）RCVBUF_ALLOCATOR</h4><ul>
<li>属于 SocketChannal 参数</li>
<li>控制 netty 接收缓冲区大小</li>
<li>负责入站数据的分配，决定入站缓冲区的大小（并可动态调整），统一采用 direct 直接内存，具体池化还是非池化由 allocator 决定</li>
</ul>
<h1 id="源码分析"><a href="#源码分析" class="headerlink" title="源码分析"></a>源码分析</h1><h3 id="启动剖析"><a href="#启动剖析" class="headerlink" title="启动剖析"></a>启动剖析</h3><p>创建selector，创建ssc，ssc通过附件注册到selectionKey，监听事件</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1 netty 中使用 NioEventLoopGroup （简称 nio boss 线程）来封装线程和 selector</span></span><br><span class="line"><span class="type">Selector</span> <span class="variable">selector</span> <span class="operator">=</span> Selector.open(); </span><br><span class="line"></span><br><span class="line"><span class="comment">//2 创建 NioServerSocketChannel，同时会初始化它关联的 handler，以及为原生 ssc 存储 config</span></span><br><span class="line"><span class="type">NioServerSocketChannel</span> <span class="variable">attachment</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioServerSocketChannel</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">//3 创建 NioServerSocketChannel 时，创建了 java 原生的 ServerSocketChannel</span></span><br><span class="line"><span class="type">ServerSocketChannel</span> <span class="variable">serverSocketChannel</span> <span class="operator">=</span> ServerSocketChannel.open(); </span><br><span class="line">serverSocketChannel.configureBlocking(<span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//4 启动 nio boss 线程执行接下来的操作</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//5 注册（仅关联 selector 和 NioServerSocketChannel），未关注事件</span></span><br><span class="line"><span class="type">SelectionKey</span> <span class="variable">selectionKey</span> <span class="operator">=</span> serverSocketChannel.register(selector, <span class="number">0</span>, attachment);</span><br><span class="line"></span><br><span class="line"><span class="comment">//6 head -&gt; 初始化器 -&gt; ServerBootstrapAcceptor -&gt; tail，初始化器是一次性的，只为添加 acceptor</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//7 绑定端口</span></span><br><span class="line">serverSocketChannel.bind(<span class="keyword">new</span> <span class="title class_">InetSocketAddress</span>(<span class="number">8080</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">//8 触发 channel active 事件，在 head 中关注 op_accept 事件</span></span><br><span class="line">selectionKey.interestOps(SelectionKey.OP_ACCEPT);</span><br></pre></td></tr></table></figure>

<p>入口 <code>io.netty.bootstrap.ServerBootstrap#bind</code></p>
<p>关键代码 <code>io.netty.bootstrap.AbstractBootstrap#doBind</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> ChannelFuture <span class="title function_">doBind</span><span class="params">(<span class="keyword">final</span> SocketAddress localAddress)</span> &#123;</span><br><span class="line">	<span class="comment">// 1. 执行初始化和注册 regFuture 会由 initAndRegister 设置其是否完成，从而回调 3.2 处代码</span></span><br><span class="line">    <span class="keyword">final</span> <span class="type">ChannelFuture</span> <span class="variable">regFuture</span> <span class="operator">=</span> initAndRegister();</span><br><span class="line">    <span class="keyword">final</span> <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> regFuture.channel();</span><br><span class="line">    <span class="keyword">if</span> (regFuture.cause() != <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> regFuture;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2. 因为是 initAndRegister 异步执行，需要分两种情况来看，调试时也需要通过 suspend 断点类型加以区分</span></span><br><span class="line">    <span class="comment">// 2.1 如果已经完成</span></span><br><span class="line">    <span class="keyword">if</span> (regFuture.isDone()) &#123;</span><br><span class="line">        <span class="type">ChannelPromise</span> <span class="variable">promise</span> <span class="operator">=</span> channel.newPromise();</span><br><span class="line">        <span class="comment">// 3.1 立刻调用 doBind0</span></span><br><span class="line">        doBind0(regFuture, channel, localAddress, promise);</span><br><span class="line">        <span class="keyword">return</span> promise;</span><br><span class="line">    &#125; </span><br><span class="line">    <span class="comment">// 2.2 还没有完成</span></span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">final</span> <span class="type">PendingRegistrationPromise</span> <span class="variable">promise</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">PendingRegistrationPromise</span>(channel);</span><br><span class="line">        <span class="comment">// 3.2 回调 doBind0</span></span><br><span class="line">        regFuture.addListener(<span class="keyword">new</span> <span class="title class_">ChannelFutureListener</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">operationComplete</span><span class="params">(ChannelFuture future)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                <span class="type">Throwable</span> <span class="variable">cause</span> <span class="operator">=</span> future.cause();</span><br><span class="line">                <span class="keyword">if</span> (cause != <span class="literal">null</span>) &#123;</span><br><span class="line">                    <span class="comment">// 处理异常...</span></span><br><span class="line">                    promise.setFailure(cause);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    promise.registered();</span><br><span class="line">					<span class="comment">// 3. 由注册线程去执行 doBind0</span></span><br><span class="line">                    doBind0(regFuture, channel, localAddress, promise);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="keyword">return</span> promise;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>步骤流程</strong></p>
<p>1.创建nioServerSocketChannel</p>
<p>关键代码 <code>io.netty.bootstrap.AbstractBootstrap#initAndRegister</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> ChannelFuture <span class="title function_">initAndRegister</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        channel = channelFactory.newChannel();<span class="comment">//会创建一个nioServerSocketChannel</span></span><br><span class="line">        <span class="comment">// 1.1 初始化 - 做的事就是添加一个初始化器 ChannelInitializer</span></span><br><span class="line">        init(channel);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        <span class="comment">// 处理异常...</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">DefaultChannelPromise</span>(<span class="keyword">new</span> <span class="title class_">FailedChannel</span>(), GlobalEventExecutor.INSTANCE).setFailure(t);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 1.2 注册 - 做的事就是将原生 channel 注册到 selector 上</span></span><br><span class="line">    <span class="type">ChannelFuture</span> <span class="variable">regFuture</span> <span class="operator">=</span> config().group().register(channel);</span><br><span class="line">    <span class="keyword">if</span> (regFuture.cause() != <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="comment">// 处理异常...</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> regFuture;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>channelFactory.newChannel();会创建一个nioServerSocketChannel，同时在nioServerSocketChannel的构造方法里面会ServerSocketChannel.open()得到原生的ssc</li>
<li>在主线程执行</li>
</ul>
<p>2.添加nioServerSocketChannel初始化handler</p>
<p>关键代码 <code>io.netty.bootstrap.ServerBootstrap#init</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 这里 channel 实际上是 NioServerSocketChannel</span></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">init</span><span class="params">(Channel channel)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">    <span class="keyword">final</span> Map&lt;ChannelOption&lt;?&gt;, Object&gt; options = options0();</span><br><span class="line">    <span class="keyword">synchronized</span> (options) &#123;</span><br><span class="line">        setChannelOptions(channel, options, logger);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> Map&lt;AttributeKey&lt;?&gt;, Object&gt; attrs = attrs0();</span><br><span class="line">    <span class="keyword">synchronized</span> (attrs) &#123;</span><br><span class="line">        <span class="keyword">for</span> (Entry&lt;AttributeKey&lt;?&gt;, Object&gt; e: attrs.entrySet()) &#123;</span><br><span class="line">            <span class="meta">@SuppressWarnings(&quot;unchecked&quot;)</span></span><br><span class="line">            AttributeKey&lt;Object&gt; key = (AttributeKey&lt;Object&gt;) e.getKey();</span><br><span class="line">            channel.attr(key).set(e.getValue());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="type">ChannelPipeline</span> <span class="variable">p</span> <span class="operator">=</span> channel.pipeline();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> <span class="type">EventLoopGroup</span> <span class="variable">currentChildGroup</span> <span class="operator">=</span> childGroup;</span><br><span class="line">    <span class="keyword">final</span> <span class="type">ChannelHandler</span> <span class="variable">currentChildHandler</span> <span class="operator">=</span> childHandler;</span><br><span class="line">    <span class="keyword">final</span> Entry&lt;ChannelOption&lt;?&gt;, Object&gt;[] currentChildOptions;</span><br><span class="line">    <span class="keyword">final</span> Entry&lt;AttributeKey&lt;?&gt;, Object&gt;[] currentChildAttrs;</span><br><span class="line">    <span class="keyword">synchronized</span> (childOptions) &#123;</span><br><span class="line">        currentChildOptions = childOptions.entrySet().toArray(newOptionArray(<span class="number">0</span>));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">synchronized</span> (childAttrs) &#123;</span><br><span class="line">        currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(<span class="number">0</span>));</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="comment">// 为 NioServerSocketChannel 添加初始化器</span></span><br><span class="line">    p.addLast(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;Channel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(<span class="keyword">final</span> Channel ch)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">            <span class="keyword">final</span> <span class="type">ChannelPipeline</span> <span class="variable">pipeline</span> <span class="operator">=</span> ch.pipeline();</span><br><span class="line">            <span class="type">ChannelHandler</span> <span class="variable">handler</span> <span class="operator">=</span> config.handler();</span><br><span class="line">            <span class="keyword">if</span> (handler != <span class="literal">null</span>) &#123;</span><br><span class="line">                pipeline.addLast(handler);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 初始化器的职责是将 ServerBootstrapAcceptor 加入至 NioServerSocketChannel</span></span><br><span class="line">            ch.eventLoop().execute(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">                    pipeline.addLast(<span class="keyword">new</span> <span class="title class_">ServerBootstrapAcceptor</span>(</span><br><span class="line">                            ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>ChannelPipeline p = channel.pipeline();得到流水线</li>
<li> p.addLast(new ChannelInitializer<Channel>() {}添加初始化handler</li>
<li>初始化handler尚未被调用</li>
</ul>
<p>3.启动nio boss线程</p>
<p>关键代码 <code>io.netty.channel.AbstractChannel.AbstractUnsafe#register</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">register</span><span class="params">(EventLoop eventLoop, <span class="keyword">final</span> ChannelPromise promise)</span> &#123;</span><br><span class="line">    <span class="comment">// 一些检查，略...</span></span><br><span class="line"></span><br><span class="line">    AbstractChannel.<span class="built_in">this</span>.eventLoop = eventLoop;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (eventLoop.inEventLoop()) &#123;<span class="comment">//当前线程是否是nio线程</span></span><br><span class="line">        register0(promise);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 首次执行 execute 方法时，会启动 nio 线程，之后注册等操作在 nio 线程上执行</span></span><br><span class="line">            <span class="comment">// 因为只有一个 NioServerSocketChannel 因此，也只会有一个 boss nio 线程</span></span><br><span class="line">            <span class="comment">// 这行代码完成的事实是 main -&gt; nio boss 线程的切换</span></span><br><span class="line">            eventLoop.execute(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">                    register0(promise);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            <span class="comment">// 日志记录...</span></span><br><span class="line">            closeForcibly();</span><br><span class="line">            closeFuture.setClosed();</span><br><span class="line">            safeSetFailure(promise, t);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>eventLoop.execute(new Runnable() {}线程切换</li>
</ul>
<p>4.原生ssc注册至selector,未关注事件</p>
<p><code>io.netty.channel.AbstractChannel.AbstractUnsafe#register0</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">register0</span><span class="params">(ChannelPromise promise)</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (!promise.setUncancellable() || !ensureOpen(promise)) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="type">boolean</span> <span class="variable">firstRegistration</span> <span class="operator">=</span> neverRegistered;</span><br><span class="line">        <span class="comment">// 1.2.1 原生的 nio channel 绑定到 selector 上，注意此时没有注册 selector 关注事件，附件为 NioServerSocketChannel</span></span><br><span class="line">        doRegister();<span class="comment">//干活的方法</span></span><br><span class="line">        neverRegistered = <span class="literal">false</span>;</span><br><span class="line">        registered = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 1.2.2 执行 NioServerSocketChannel 初始化器的 initChannel</span></span><br><span class="line">        pipeline.invokeHandlerAddedIfNeeded();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 回调 3.2 io.netty.bootstrap.AbstractBootstrap#doBind0</span></span><br><span class="line">        safeSetSuccess(promise);</span><br><span class="line">        pipeline.fireChannelRegistered();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 对应 server socket channel 还未绑定，isActive 为 false</span></span><br><span class="line">        <span class="keyword">if</span> (isActive()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (firstRegistration) &#123;</span><br><span class="line">                pipeline.fireChannelActive();</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (config().isAutoRead()) &#123;</span><br><span class="line">                beginRead();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        <span class="comment">// Close the channel directly to avoid FD leak.</span></span><br><span class="line">        closeForcibly();</span><br><span class="line">        closeFuture.setClosed();</span><br><span class="line">        safeSetFailure(promise, t);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>pipeline.invokeHandlerAddedIfNeeded();执行 NioServerSocketChannel 初始化器的 initChannel</li>
</ul>
<p>5.执行</p>
<p>关键代码 <code>io.netty.channel.ChannelInitializer#initChannel</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="type">boolean</span> <span class="title function_">initChannel</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">    <span class="keyword">if</span> (initMap.add(ctx)) &#123; <span class="comment">// Guard against re-entrance.</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 1.2.2.1 执行初始化</span></span><br><span class="line">            initChannel((C) ctx.channel());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable cause) &#123;</span><br><span class="line">            exceptionCaught(ctx, cause);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">// 1.2.2.2 移除初始化器</span></span><br><span class="line">            <span class="type">ChannelPipeline</span> <span class="variable">pipeline</span> <span class="operator">=</span> ctx.pipeline();</span><br><span class="line">            <span class="keyword">if</span> (pipeline.context(<span class="built_in">this</span>) != <span class="literal">null</span>) &#123;</span><br><span class="line">                pipeline.remove(<span class="built_in">this</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>6.regFuture回调doBind0</p>
<p>关键代码 <code>io.netty.bootstrap.AbstractBootstrap#doBind0</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 3.1 或 3.2 执行 doBind0</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">doBind0</span><span class="params">(</span></span><br><span class="line"><span class="params">        <span class="keyword">final</span> ChannelFuture regFuture, <span class="keyword">final</span> Channel channel,</span></span><br><span class="line"><span class="params">        <span class="keyword">final</span> SocketAddress localAddress, <span class="keyword">final</span> ChannelPromise promise)</span> &#123;</span><br><span class="line"></span><br><span class="line">    channel.eventLoop().execute(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (regFuture.isSuccess()) &#123;</span><br><span class="line">                channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                promise.setFailure(regFuture.cause());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>regFuture添加了addListener，当有返回结果时回调dobind0</li>
</ul>
<p>关键代码 <code>io.netty.channel.AbstractChannel.AbstractUnsafe#bind</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">bind</span><span class="params">(<span class="keyword">final</span> SocketAddress localAddress, <span class="keyword">final</span> ChannelPromise promise)</span> &#123;</span><br><span class="line">    assertEventLoop();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!promise.setUncancellable() || !ensureOpen(promise)) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) &amp;&amp;</span><br><span class="line">        localAddress <span class="keyword">instanceof</span> InetSocketAddress &amp;&amp;</span><br><span class="line">        !((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() &amp;&amp;</span><br><span class="line">        !PlatformDependent.isWindows() &amp;&amp; !PlatformDependent.maybeSuperUser()) &#123;</span><br><span class="line">        <span class="comment">// 记录日志...</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="type">boolean</span> <span class="variable">wasActive</span> <span class="operator">=</span> isActive();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 3.3 执行端口绑定</span></span><br><span class="line">        doBind(localAddress);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        safeSetFailure(promise, t);</span><br><span class="line">        closeIfClosed();</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!wasActive &amp;&amp; isActive()) &#123;</span><br><span class="line">        invokeLater(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">                <span class="comment">// 3.4 触发 active 事件</span></span><br><span class="line">                pipeline.fireChannelActive();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    safeSetSuccess(promise);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>3.3 关键代码 <code>io.netty.channel.socket.nio.NioServerSocketChannel#doBind</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doBind</span><span class="params">(SocketAddress localAddress)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">    <span class="keyword">if</span> (PlatformDependent.javaVersion() &gt;= <span class="number">7</span>) &#123;</span><br><span class="line">        javaChannel().bind(localAddress, config.getBacklog());</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        javaChannel().socket().bind(localAddress, config.getBacklog());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>ssc绑定端口号</li>
</ul>
<p>3.4 关键代码 <code>io.netty.channel.DefaultChannelPipeline.HeadContext#channelActive</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> &#123;</span><br><span class="line">    ctx.fireChannelActive();</span><br><span class="line">	<span class="comment">// 触发 read (NioServerSocketChannel 上的 read 不是读取数据，只是为了触发 channel 的事件注册)</span></span><br><span class="line">    readIfIsAutoRead();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后关注accept事件</p>
<p>关键代码 <code>io.netty.channel.nio.AbstractNioChannel#doBeginRead</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doBeginRead</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">    <span class="comment">// Channel.read() or ChannelHandlerContext.read() was called</span></span><br><span class="line">    <span class="keyword">final</span> <span class="type">SelectionKey</span> <span class="variable">selectionKey</span> <span class="operator">=</span> <span class="built_in">this</span>.selectionKey;</span><br><span class="line">    <span class="keyword">if</span> (!selectionKey.isValid()) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    readPending = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> <span class="type">int</span> <span class="variable">interestOps</span> <span class="operator">=</span> selectionKey.interestOps();</span><br><span class="line">    <span class="comment">// readInterestOp 取值是 16，在 NioServerSocketChannel 创建时初始化好，代表关注 accept 事件</span></span><br><span class="line">    <span class="keyword">if</span> ((interestOps &amp; readInterestOp) == <span class="number">0</span>) &#123;</span><br><span class="line">        selectionKey.interestOps(interestOps | readInterestOp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="NioEventLoop-剖析"><a href="#NioEventLoop-剖析" class="headerlink" title="NioEventLoop 剖析"></a>NioEventLoop 剖析</h3><p>NioEventLoop 源码900行，再加上各个父类，有点重量级…</p>
<h4 id="NioEventLoop的组成"><a href="#NioEventLoop的组成" class="headerlink" title="NioEventLoop的组成"></a>NioEventLoop的组成</h4><p>selector</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> Selector selector;</span><br><span class="line"><span class="keyword">private</span> Selector unwrappedSelector;</span><br></pre></td></tr></table></figure>

<p>线程和任务队列</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在父类SingleThreadEventExecutor</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Queue&lt;Runnable&gt; taskQueue;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">volatile</span> Thread thread;</span><br><span class="line"></span><br><span class="line"><span class="comment">//更上级的父类里AbstractScheduledEventExecutor处理定时任务的任务队列</span></span><br><span class="line">PriorityQueue&lt;ScheduledFutureTask&lt;?&gt;&gt; scheduledTaskQueue;</span><br></pre></td></tr></table></figure>

<h4 id="selector的创建"><a href="#selector的创建" class="headerlink" title="selector的创建"></a>selector的创建</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//构造方法中创建</span></span><br><span class="line">NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider, SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler, EventLoopTaskQueueFactory queueFactory) &#123;</span><br><span class="line">    <span class="built_in">super</span>(parent, executor, <span class="literal">false</span>, newTaskQueue(queueFactory), newTaskQueue(queueFactory), rejectedExecutionHandler);</span><br><span class="line">    <span class="keyword">if</span> (selectorProvider == <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NullPointerException</span>(<span class="string">&quot;selectorProvider&quot;</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (strategy == <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NullPointerException</span>(<span class="string">&quot;selectStrategy&quot;</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.provider = selectorProvider;</span><br><span class="line">        NioEventLoop.<span class="type">SelectorTuple</span> <span class="variable">selectorTuple</span> <span class="operator">=</span> <span class="built_in">this</span>.openSelector();<span class="comment">//创建selector</span></span><br><span class="line">        <span class="built_in">this</span>.selector = selectorTuple.selector;</span><br><span class="line">        <span class="built_in">this</span>.unwrappedSelector = selectorTuple.unwrappedSelector;</span><br><span class="line">        <span class="built_in">this</span>.selectStrategy = strategy;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> NioEventLoop.SelectorTuple <span class="title function_">openSelector</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">final</span> AbstractSelector unwrappedSelector;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        unwrappedSelector = <span class="built_in">this</span>.provider.openSelector();<span class="comment">//unwrappedSelector没包装的selector</span></span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException var7) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">ChannelException</span>(<span class="string">&quot;failed to open a new selector&quot;</span>, var7);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>为何会有两个selector</p>
<p>将通过数组实现的Selector采用反射替换了基于hashset实现的selector，用来遍历selectesKey时提升性能</p>
</li>
</ul>
<h4 id="NioEventLoop-的nio线程"><a href="#NioEventLoop-的nio线程" class="headerlink" title="NioEventLoop 的nio线程"></a>NioEventLoop 的nio线程</h4><p>NioEventLoop 线程不仅要处理 IO 事件，还要处理 Task（包括普通任务和定时任务）</p>
<p>当调用execute()时启动nio线程，startThread()中将状态位state改为STARTED，保证线程只启动一次，然后调用doStartThread()方法</p>
<p>提交任务代码 <code>io.netty.util.concurrent.SingleThreadEventExecutor#execute</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">execute</span><span class="params">(Runnable task)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (task == <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NullPointerException</span>(<span class="string">&quot;task&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="type">boolean</span> <span class="variable">inEventLoop</span> <span class="operator">=</span> inEventLoop();</span><br><span class="line">    <span class="comment">// 添加任务，其中队列使用了 jctools 提供的 mpsc 无锁队列</span></span><br><span class="line">    addTask(task);</span><br><span class="line">    <span class="keyword">if</span> (!inEventLoop) &#123;</span><br><span class="line">        <span class="comment">// inEventLoop 如果为 false 表示由其它线程来调用 execute，即首次调用，这时需要向 eventLoop 提交首个任务，启动死循环，会执行到下面的 doStartThread</span></span><br><span class="line">        startThread();</span><br><span class="line">        <span class="keyword">if</span> (isShutdown()) &#123;</span><br><span class="line">            <span class="comment">// 如果已经 shutdown，做拒绝逻辑，代码略...</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!addTaskWakesUp &amp;&amp; wakesUpForTask(task)) &#123;</span><br><span class="line">        <span class="comment">// 如果线程由于 IO select 阻塞了，添加的任务的线程需要负责唤醒 NioEventLoop 线程</span></span><br><span class="line">        wakeup(inEventLoop);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>提交任务时唤醒 select 阻塞线程<code>io.netty.channel.nio.NioEventLoop#wakeup</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">wakeup</span><span class="params">(<span class="type">boolean</span> inEventLoop)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (!inEventLoop &amp;&amp; wakenUp.compareAndSet(<span class="literal">false</span>, <span class="literal">true</span>)) &#123;</span><br><span class="line">        selector.wakeup();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>wakenUp原子变量记录是否已经被唤醒了，避免多个线程频繁的wakeup()</li>
</ul>
<p>启动 EventLoop 主循环 <code>io.netty.util.concurrent.SingleThreadEventExecutor#doStartThread</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">doStartThread</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">assert</span> <span class="variable">thread</span> <span class="operator">=</span>= <span class="literal">null</span>;</span><br><span class="line">    executor.execute(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">            <span class="comment">// 将线程池的当前线程保存在成员变量中，以便后续使用</span></span><br><span class="line">            thread = Thread.currentThread();</span><br><span class="line">            <span class="keyword">if</span> (interrupted) &#123;</span><br><span class="line">                thread.interrupt();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="type">boolean</span> <span class="variable">success</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line">            updateLastExecutionTime();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">// 调用外部类 SingleThreadEventExecutor 的 run 方法，进入死循环，run 方法见下</span></span><br><span class="line">                SingleThreadEventExecutor.<span class="built_in">this</span>.run();</span><br><span class="line">                success = <span class="literal">true</span>;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">                logger.warn(<span class="string">&quot;Unexpected exception from an event executor: &quot;</span>, t);</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">				<span class="comment">// 清理工作，代码略...</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>io.netty.channel.nio.NioEventLoop#run</code> 主要任务是执行死循环，不断看有没有新任务，有没有 IO 事件</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">// calculateStrategy 的逻辑如下：</span></span><br><span class="line">                <span class="comment">// 有任务，会执行一次 selectNow，清除上一次的 wakeup 结果，无论有没有 IO 事件，都会跳过 switch</span></span><br><span class="line">                <span class="comment">// 没有任务，会匹配 SelectStrategy.SELECT，看是否应当阻塞</span></span><br><span class="line">                <span class="keyword">switch</span> (selectStrategy.calculateStrategy(selectNowSupplier, hasTasks())) &#123;</span><br><span class="line">                    <span class="keyword">case</span> SelectStrategy.CONTINUE:</span><br><span class="line">                        <span class="keyword">continue</span>;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">case</span> SelectStrategy.BUSY_WAIT:</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">case</span> SelectStrategy.SELECT:</span><br><span class="line">                        <span class="comment">// 因为 IO 线程和提交任务线程都有可能执行 wakeup，而 wakeup 属于比较昂贵的操作，因此使用了一个原子布尔对象 wakenUp，它取值为 true 时，表示该由当前线程唤醒</span></span><br><span class="line">                        <span class="comment">// 进行 select 阻塞，并设置唤醒状态为 false</span></span><br><span class="line">                        <span class="type">boolean</span> <span class="variable">oldWakenUp</span> <span class="operator">=</span> wakenUp.getAndSet(<span class="literal">false</span>);</span><br><span class="line">                        </span><br><span class="line">                        <span class="comment">// 如果在这个位置，非 EventLoop 线程抢先将 wakenUp 置为 true，并 wakeup</span></span><br><span class="line">                        <span class="comment">// 下面的 select 方法不会阻塞</span></span><br><span class="line">                        <span class="comment">// 等 runAllTasks 处理完成后，到再循环进来这个阶段新增的任务会不会及时执行呢?</span></span><br><span class="line">                        <span class="comment">// 因为 oldWakenUp 为 true，因此下面的 select 方法就会阻塞，直到超时</span></span><br><span class="line">                        <span class="comment">// 才能执行，让 select 方法无谓阻塞</span></span><br><span class="line">                        select(oldWakenUp);</span><br><span class="line"></span><br><span class="line">                        <span class="keyword">if</span> (wakenUp.get()) &#123;</span><br><span class="line">                            selector.wakeup();</span><br><span class="line">                        &#125;</span><br><span class="line">                    <span class="keyword">default</span>:</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                rebuildSelector0();</span><br><span class="line">                handleLoopException(e);</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            cancelledKeys = <span class="number">0</span>;</span><br><span class="line">            needsToSelectAgain = <span class="literal">false</span>;</span><br><span class="line">            <span class="comment">// ioRatio 默认是 50</span></span><br><span class="line">            <span class="keyword">final</span> <span class="type">int</span> <span class="variable">ioRatio</span> <span class="operator">=</span> <span class="built_in">this</span>.ioRatio;</span><br><span class="line">            <span class="keyword">if</span> (ioRatio == <span class="number">100</span>) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    processSelectedKeys();</span><br><span class="line">                &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                    <span class="comment">// ioRatio 为 100 时，总是运行完所有非 IO 任务</span></span><br><span class="line">                    runAllTasks();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;                </span><br><span class="line">                <span class="keyword">final</span> <span class="type">long</span> <span class="variable">ioStartTime</span> <span class="operator">=</span> System.nanoTime();</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    processSelectedKeys();</span><br><span class="line">                &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                    <span class="comment">// 记录 io 事件处理耗时</span></span><br><span class="line">                    <span class="keyword">final</span> <span class="type">long</span> <span class="variable">ioTime</span> <span class="operator">=</span> System.nanoTime() - ioStartTime;</span><br><span class="line">                    <span class="comment">// 运行非 IO 任务，一旦超时会退出 runAllTasks</span></span><br><span class="line">                    runAllTasks(ioTime * (<span class="number">100</span> - ioRatio) / ioRatio);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            handleLoopException(t);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (isShuttingDown()) &#123;</span><br><span class="line">                closeAll();</span><br><span class="line">                <span class="keyword">if</span> (confirmShutdown()) &#123;</span><br><span class="line">                    <span class="keyword">return</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            handleLoopException(t);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>calculateStrategy 的逻辑</p>
<ul>
<li>有任务，会执行一次 selectNow，清除上一次的 wakeup 结果，无论有没有 IO 事件，都会跳过 switch</li>
<li>没有任务，会匹配 SelectStrategy.SELECT，看是否应当阻塞</li>
</ul>
<p>注意</p>
<blockquote>
<p>这里有个费解的地方就是 wakeup，它既可以由提交任务的线程来调用（比较好理解），也可以由 EventLoop 线程来调用（比较费解），这里要知道 wakeup 方法的效果：</p>
<ul>
<li>由非 EventLoop 线程调用，会唤醒当前在执行 select 阻塞的 EventLoop 线程</li>
<li>由 EventLoop 自己调用，会本次的 wakeup 会取消下一次的 select 操作</li>
</ul>
</blockquote>
<p>参考下图</p>
<img src="https://zqyhdm-blog.oss-cn-shanghai.aliyuncs.com/markdown/0032.png"  />



<p><code>io.netty.channel.nio.NioEventLoop#select</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">select</span><span class="params">(<span class="type">boolean</span> oldWakenUp)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">    <span class="type">Selector</span> <span class="variable">selector</span> <span class="operator">=</span> <span class="built_in">this</span>.selector;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">selectCnt</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="type">long</span> <span class="variable">currentTimeNanos</span> <span class="operator">=</span> System.nanoTime();</span><br><span class="line">        <span class="comment">// 计算等待时间</span></span><br><span class="line">        <span class="comment">// * 没有 scheduledTask，超时时间为 1s</span></span><br><span class="line">        <span class="comment">// * 有 scheduledTask，超时时间为 `下一个定时任务执行时间 - 当前时间`</span></span><br><span class="line">        <span class="type">long</span> <span class="variable">selectDeadLineNanos</span> <span class="operator">=</span> currentTimeNanos + delayNanos(currentTimeNanos);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">            <span class="comment">//超时时间的计算</span></span><br><span class="line">            <span class="type">long</span> <span class="variable">timeoutMillis</span> <span class="operator">=</span> (selectDeadLineNanos - currentTimeNanos + <span class="number">500000L</span>) / <span class="number">1000000L</span>;</span><br><span class="line">            <span class="comment">// 如果超时，退出循环</span></span><br><span class="line">            <span class="keyword">if</span> (timeoutMillis &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (selectCnt == <span class="number">0</span>) &#123;</span><br><span class="line">                    selector.selectNow();</span><br><span class="line">                    selectCnt = <span class="number">1</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 如果期间又有 task 退出循环，如果没这个判断，那么任务就会等到下次 select 超时时才能被执行</span></span><br><span class="line">            <span class="comment">// wakenUp.compareAndSet(false, true) 是让非 NioEventLoop 不必再执行 wakeup</span></span><br><span class="line">            <span class="keyword">if</span> (hasTasks() &amp;&amp; wakenUp.compareAndSet(<span class="literal">false</span>, <span class="literal">true</span>)) &#123;</span><br><span class="line">                selector.selectNow();</span><br><span class="line">                selectCnt = <span class="number">1</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// select 有限时阻塞</span></span><br><span class="line">            <span class="type">int</span> <span class="variable">selectedKeys</span> <span class="operator">=</span> selector.select(timeoutMillis);</span><br><span class="line">            <span class="comment">// 计数加 1</span></span><br><span class="line">            selectCnt ++;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 醒来后，如果有 IO 事件、或是由非 EventLoop 线程唤醒，或者有任务，退出循环</span></span><br><span class="line">            <span class="keyword">if</span> (selectedKeys != <span class="number">0</span> || oldWakenUp || wakenUp.get() || hasTasks() || hasScheduledTasks()) &#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (Thread.interrupted()) &#123;</span><br><span class="line">               	<span class="comment">// 线程被打断，退出循环</span></span><br><span class="line">                <span class="comment">// 记录日志</span></span><br><span class="line">                selectCnt = <span class="number">1</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="type">long</span> <span class="variable">time</span> <span class="operator">=</span> System.nanoTime();</span><br><span class="line">            <span class="keyword">if</span> (time - TimeUnit.MILLISECONDS.toNanos(timeoutMillis) &gt;= currentTimeNanos) &#123;</span><br><span class="line">                <span class="comment">// 如果超时，计数重置为 1，下次循环就会 break</span></span><br><span class="line">                selectCnt = <span class="number">1</span>;</span><br><span class="line">            &#125; </span><br><span class="line">            <span class="comment">// 计数超过阈值，由 io.netty.selectorAutoRebuildThreshold 指定，默认 512</span></span><br><span class="line">            <span class="comment">// 这是为了解决 nio 空轮询 bug</span></span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (SELECTOR_AUTO_REBUILD_THRESHOLD &gt; <span class="number">0</span> &amp;&amp;</span><br><span class="line">                    selectCnt &gt;= SELECTOR_AUTO_REBUILD_THRESHOLD) &#123;</span><br><span class="line">                <span class="comment">// 重建 selector，替换掉旧的selector</span></span><br><span class="line">                selector = selectRebuildSelector(selectCnt);</span><br><span class="line">                selectCnt = <span class="number">1</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            currentTimeNanos = time;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (selectCnt &gt; MIN_PREMATURE_SELECTOR_RETURNS) &#123;</span><br><span class="line">            <span class="comment">// 记录日志</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (CancelledKeyException e) &#123;</span><br><span class="line">        <span class="comment">// 记录日志</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>没有定时任务时，long selectDeadLineNanos = currentTimeNanos + delayNanos(currentTimeNanos);截至时间就是当前时间+1s，long timeoutMillis = (selectDeadLineNanos - currentTimeNanos + 500000L) / 1000000L;超时时间=截至时间-当前时间+0.5ms，也就是差不多1s</li>
<li>当有任务，或者超时时间到了退出循环</li>
</ul>
<p>区分不同类型的事件</p>
<p><code>io.netty.channel.nio.NioEventLoop#processSelectedKey</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">processSelectedKey</span><span class="params">(SelectionKey k, AbstractNioChannel ch)</span> &#123;</span><br><span class="line">    <span class="keyword">final</span> AbstractNioChannel.<span class="type">NioUnsafe</span> <span class="variable">unsafe</span> <span class="operator">=</span> ch.unsafe();</span><br><span class="line">    <span class="comment">// 当 key 取消或关闭时会导致这个 key 无效</span></span><br><span class="line">    <span class="keyword">if</span> (!k.isValid()) &#123;</span><br><span class="line">        <span class="comment">// 无效时处理...</span></span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">readyOps</span> <span class="operator">=</span> k.readyOps();</span><br><span class="line">        <span class="comment">// 连接事件</span></span><br><span class="line">        <span class="keyword">if</span> ((readyOps &amp; SelectionKey.OP_CONNECT) != <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">ops</span> <span class="operator">=</span> k.interestOps();</span><br><span class="line">            ops &amp;= ~SelectionKey.OP_CONNECT;</span><br><span class="line">            k.interestOps(ops);</span><br><span class="line"></span><br><span class="line">            unsafe.finishConnect();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 可写事件</span></span><br><span class="line">        <span class="keyword">if</span> ((readyOps &amp; SelectionKey.OP_WRITE) != <span class="number">0</span>) &#123;</span><br><span class="line">            ch.unsafe().forceFlush();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 可读或可接入事件</span></span><br><span class="line">        <span class="keyword">if</span> ((readyOps &amp; (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != <span class="number">0</span> || readyOps == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">// 如果是可接入 io.netty.channel.nio.AbstractNioMessageChannel.NioMessageUnsafe#read</span></span><br><span class="line">            <span class="comment">// 如果是可读 io.netty.channel.nio.AbstractNioByteChannel.NioByteUnsafe#read</span></span><br><span class="line">            unsafe.read();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (CancelledKeyException ignored) &#123;</span><br><span class="line">        unsafe.close(unsafe.voidPromise());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="accept-剖析"><a href="#accept-剖析" class="headerlink" title="accept 剖析"></a>accept 剖析</h3><p>nio 中如下代码，在 netty 中的流程</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1 阻塞直到事件发生</span></span><br><span class="line">selector.select();</span><br><span class="line"></span><br><span class="line">Iterator&lt;SelectionKey&gt; iter = selector.selectedKeys().iterator();</span><br><span class="line"><span class="keyword">while</span> (iter.hasNext()) &#123;    </span><br><span class="line">    <span class="comment">//2 拿到一个事件</span></span><br><span class="line">    <span class="type">SelectionKey</span> <span class="variable">key</span> <span class="operator">=</span> iter.next();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//3 如果是 accept 事件</span></span><br><span class="line">    <span class="keyword">if</span> (key.isAcceptable()) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//4 执行 accept</span></span><br><span class="line">        <span class="type">SocketChannel</span> <span class="variable">channel</span> <span class="operator">=</span> serverSocketChannel.accept();</span><br><span class="line">        channel.configureBlocking(<span class="literal">false</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//5 关注 read 事件</span></span><br><span class="line">        channel.register(selector, SelectionKey.OP_READ);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>先来看可接入事件处理（accept）</p>
<p><code>io.netty.channel.nio.AbstractNioMessageChannel.NioMessageUnsafe#read</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">read</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">assert</span> <span class="title function_">eventLoop</span><span class="params">()</span>.inEventLoop();</span><br><span class="line">    <span class="keyword">final</span> <span class="type">ChannelConfig</span> <span class="variable">config</span> <span class="operator">=</span> config();</span><br><span class="line">    <span class="keyword">final</span> <span class="type">ChannelPipeline</span> <span class="variable">pipeline</span> <span class="operator">=</span> pipeline();    </span><br><span class="line">    <span class="keyword">final</span> RecvByteBufAllocator.<span class="type">Handle</span> <span class="variable">allocHandle</span> <span class="operator">=</span> unsafe().recvBufAllocHandle();</span><br><span class="line">    allocHandle.reset(config);</span><br><span class="line"></span><br><span class="line">    <span class="type">boolean</span> <span class="variable">closed</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="type">Throwable</span> <span class="variable">exception</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">do</span> &#123;</span><br><span class="line">				<span class="comment">// doReadMessages 中执行了 accept 并创建 NioSocketChannel 作为消息放入 readBuf</span></span><br><span class="line">                <span class="comment">// readBuf 是一个 ArrayList 用来缓存消息</span></span><br><span class="line">                <span class="type">int</span> <span class="variable">localRead</span> <span class="operator">=</span> doReadMessages(readBuf);</span><br><span class="line">                <span class="keyword">if</span> (localRead == <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (localRead &lt; <span class="number">0</span>) &#123;</span><br><span class="line">                    closed = <span class="literal">true</span>;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">				<span class="comment">// localRead 为 1，就一条消息，即接收一个客户端连接</span></span><br><span class="line">                allocHandle.incMessagesRead(localRead);</span><br><span class="line">            &#125; <span class="keyword">while</span> (allocHandle.continueReading());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            exception = t;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="type">int</span> <span class="variable">size</span> <span class="operator">=</span> readBuf.size();</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; size; i ++) &#123;</span><br><span class="line">            readPending = <span class="literal">false</span>;</span><br><span class="line">            <span class="comment">// 触发 read 事件，让 pipeline 上的 handler 处理，这时是处理</span></span><br><span class="line">            <span class="comment">// io.netty.bootstrap.ServerBootstrap.ServerBootstrapAcceptor#channelRead</span></span><br><span class="line">            pipeline.fireChannelRead(readBuf.get(i));</span><br><span class="line">        &#125;</span><br><span class="line">        readBuf.clear();</span><br><span class="line">        allocHandle.readComplete();</span><br><span class="line">        pipeline.fireChannelReadComplete();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (exception != <span class="literal">null</span>) &#123;</span><br><span class="line">            closed = closeOnReadError(exception);</span><br><span class="line"></span><br><span class="line">            pipeline.fireExceptionCaught(exception);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (closed) &#123;</span><br><span class="line">            inputShutdown = <span class="literal">true</span>;</span><br><span class="line">            <span class="keyword">if</span> (isOpen()) &#123;</span><br><span class="line">                close(voidPromise());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (!readPending &amp;&amp; !config.isAutoRead()) &#123;</span><br><span class="line">            removeReadOp();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>关键代码 <code>io.netty.bootstrap.ServerBootstrap.ServerBootstrapAcceptor#channelRead</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> &#123;</span><br><span class="line">    <span class="comment">// 这时的 msg 是 NioSocketChannel</span></span><br><span class="line">    <span class="keyword">final</span> <span class="type">Channel</span> <span class="variable">child</span> <span class="operator">=</span> (Channel) msg;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// NioSocketChannel 添加  childHandler 即初始化器</span></span><br><span class="line">    child.pipeline().addLast(childHandler);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 设置选项</span></span><br><span class="line">    setChannelOptions(child, childOptions, logger);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (Entry&lt;AttributeKey&lt;?&gt;, Object&gt; e: childAttrs) &#123;</span><br><span class="line">        child.attr((AttributeKey&lt;Object&gt;) e.getKey()).set(e.getValue());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 注册 NioSocketChannel 到 nio worker 线程，接下来的处理也移交至 nio worker 线程</span></span><br><span class="line">        childGroup.register(child).addListener(<span class="keyword">new</span> <span class="title class_">ChannelFutureListener</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">operationComplete</span><span class="params">(ChannelFuture future)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                <span class="keyword">if</span> (!future.isSuccess()) &#123;</span><br><span class="line">                    forceClose(child, future.cause());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        forceClose(child, t);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>又回到了熟悉的 <code>io.netty.channel.AbstractChannel.AbstractUnsafe#register</code>  方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">register</span><span class="params">(EventLoop eventLoop, <span class="keyword">final</span> ChannelPromise promise)</span> &#123;</span><br><span class="line">    <span class="comment">// 一些检查，略...</span></span><br><span class="line"></span><br><span class="line">    AbstractChannel.<span class="built_in">this</span>.eventLoop = eventLoop;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (eventLoop.inEventLoop()) &#123;</span><br><span class="line">        register0(promise);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 这行代码完成的事实是 nio boss -&gt; nio worker 线程的切换</span></span><br><span class="line">            eventLoop.execute(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">                    register0(promise);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            <span class="comment">// 日志记录...</span></span><br><span class="line">            closeForcibly();</span><br><span class="line">            closeFuture.setClosed();</span><br><span class="line">            safeSetFailure(promise, t);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>io.netty.channel.AbstractChannel.AbstractUnsafe#register0</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">register0</span><span class="params">(ChannelPromise promise)</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (!promise.setUncancellable() || !ensureOpen(promise)) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="type">boolean</span> <span class="variable">firstRegistration</span> <span class="operator">=</span> neverRegistered;</span><br><span class="line">        doRegister();</span><br><span class="line">        neverRegistered = <span class="literal">false</span>;</span><br><span class="line">        registered = <span class="literal">true</span>;</span><br><span class="line">		</span><br><span class="line">        <span class="comment">// 执行初始化器，执行前 pipeline 中只有 head -&gt; 初始化器 -&gt; tail</span></span><br><span class="line">        pipeline.invokeHandlerAddedIfNeeded();</span><br><span class="line">        <span class="comment">// 执行后就是 head -&gt; logging handler -&gt; my handler -&gt; tail</span></span><br><span class="line"></span><br><span class="line">        safeSetSuccess(promise);</span><br><span class="line">        pipeline.fireChannelRegistered();</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (isActive()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (firstRegistration) &#123;</span><br><span class="line">                <span class="comment">// 触发 pipeline 上 active 事件</span></span><br><span class="line">                pipeline.fireChannelActive();</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (config().isAutoRead()) &#123;</span><br><span class="line">                beginRead();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        closeForcibly();</span><br><span class="line">        closeFuture.setClosed();</span><br><span class="line">        safeSetFailure(promise, t);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>回到了熟悉的代码 <code>io.netty.channel.DefaultChannelPipeline.HeadContext#channelActive</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> &#123;</span><br><span class="line">    ctx.fireChannelActive();</span><br><span class="line">	<span class="comment">// 触发 read (NioSocketChannel 这里 read，只是为了触发 channel 的事件注册，还未涉及数据读取)</span></span><br><span class="line">    readIfIsAutoRead();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>io.netty.channel.nio.AbstractNioChannel#doBeginRead</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doBeginRead</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">    <span class="comment">// Channel.read() or ChannelHandlerContext.read() was called</span></span><br><span class="line">    <span class="keyword">final</span> <span class="type">SelectionKey</span> <span class="variable">selectionKey</span> <span class="operator">=</span> <span class="built_in">this</span>.selectionKey;</span><br><span class="line">    <span class="keyword">if</span> (!selectionKey.isValid()) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    readPending = <span class="literal">true</span>;</span><br><span class="line">	<span class="comment">// 这时候 interestOps 是 0</span></span><br><span class="line">    <span class="keyword">final</span> <span class="type">int</span> <span class="variable">interestOps</span> <span class="operator">=</span> selectionKey.interestOps();</span><br><span class="line">    <span class="keyword">if</span> ((interestOps &amp; readInterestOp) == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">// 关注 read 事件</span></span><br><span class="line">        selectionKey.interestOps(interestOps | readInterestOp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="read-剖析"><a href="#read-剖析" class="headerlink" title="read 剖析"></a>read 剖析</h3><p>再来看可读事件 <code>io.netty.channel.nio.AbstractNioByteChannel.NioByteUnsafe#read</code>，注意发送的数据未必能够一次读完，因此会触发多次 nio read 事件，一次事件内会触发多次 pipeline read，一次事件会触发一次 pipeline read complete</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">read</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">final</span> <span class="type">ChannelConfig</span> <span class="variable">config</span> <span class="operator">=</span> config();</span><br><span class="line">    <span class="keyword">if</span> (shouldBreakReadReady(config)) &#123;</span><br><span class="line">        clearReadPending();</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">final</span> <span class="type">ChannelPipeline</span> <span class="variable">pipeline</span> <span class="operator">=</span> pipeline();</span><br><span class="line">    <span class="comment">// io.netty.allocator.type 决定 allocator 的实现</span></span><br><span class="line">    <span class="keyword">final</span> <span class="type">ByteBufAllocator</span> <span class="variable">allocator</span> <span class="operator">=</span> config.getAllocator();</span><br><span class="line">    <span class="comment">// 用来分配 byteBuf，确定单次读取大小</span></span><br><span class="line">    <span class="keyword">final</span> RecvByteBufAllocator.<span class="type">Handle</span> <span class="variable">allocHandle</span> <span class="operator">=</span> recvBufAllocHandle();</span><br><span class="line">    allocHandle.reset(config);</span><br><span class="line"></span><br><span class="line">    <span class="type">ByteBuf</span> <span class="variable">byteBuf</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="type">boolean</span> <span class="variable">close</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">            byteBuf = allocHandle.allocate(allocator);</span><br><span class="line">            <span class="comment">// 读取</span></span><br><span class="line">            allocHandle.lastBytesRead(doReadBytes(byteBuf));</span><br><span class="line">            <span class="keyword">if</span> (allocHandle.lastBytesRead() &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">                byteBuf.release();</span><br><span class="line">                byteBuf = <span class="literal">null</span>;</span><br><span class="line">                close = allocHandle.lastBytesRead() &lt; <span class="number">0</span>;</span><br><span class="line">                <span class="keyword">if</span> (close) &#123;</span><br><span class="line">                    readPending = <span class="literal">false</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            allocHandle.incMessagesRead(<span class="number">1</span>);</span><br><span class="line">            readPending = <span class="literal">false</span>;</span><br><span class="line">            <span class="comment">// 触发 read 事件，让 pipeline 上的 handler 处理，这时是处理 NioSocketChannel 上的 handler</span></span><br><span class="line">            pipeline.fireChannelRead(byteBuf);</span><br><span class="line">            byteBuf = <span class="literal">null</span>;</span><br><span class="line">        &#125; </span><br><span class="line">        <span class="comment">// 是否要继续循环</span></span><br><span class="line">        <span class="keyword">while</span> (allocHandle.continueReading());</span><br><span class="line"></span><br><span class="line">        allocHandle.readComplete();</span><br><span class="line">        <span class="comment">// 触发 read complete 事件</span></span><br><span class="line">        pipeline.fireChannelReadComplete();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (close) &#123;</span><br><span class="line">            closeOnRead(pipeline);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        handleReadException(pipeline, byteBuf, t, close, allocHandle);</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (!readPending &amp;&amp; !config.isAutoRead()) &#123;</span><br><span class="line">            removeReadOp();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><code>io.netty.channel.DefaultMaxMessagesRecvByteBufAllocator.MaxMessageHandle#continueReading(io.netty.util.UncheckedBooleanSupplier)</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">continueReading</span><span class="params">(UncheckedBooleanSupplier maybeMoreDataSupplier)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> </span><br><span class="line">           <span class="comment">// 一般为 true</span></span><br><span class="line">           config.isAutoRead() &amp;&amp;</span><br><span class="line">           <span class="comment">// respectMaybeMoreData 默认为 true</span></span><br><span class="line">           <span class="comment">// maybeMoreDataSupplier 的逻辑是如果预期读取字节与实际读取字节相等，返回 true</span></span><br><span class="line">           (!respectMaybeMoreData || maybeMoreDataSupplier.get()) &amp;&amp;</span><br><span class="line">           <span class="comment">// 小于最大次数，maxMessagePerRead 默认 16</span></span><br><span class="line">           totalMessages &lt; maxMessagePerRead &amp;&amp;</span><br><span class="line">           <span class="comment">// 实际读到了数据</span></span><br><span class="line">           totalBytesRead &gt; <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>




      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://skyung.gitee.io/Skyung/2022/04/20/netty/" title="Netty" target="_blank" rel="external">https://skyung.gitee.io/Skyung/2022/04/20/netty/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://github.com/cofess" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/Skyung/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://github.com/cofess" target="_blank"><span class="text-dark">Skyung</span><small class="ml-1x">Web Developer</small></a></h3>
        <div>脚踏实地，仰望星空</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="uyan_frame"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/Skyung/2022/04/20/java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" title="JVM并发编程"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/Skyung/2022/04/12/java%E6%B7%B1%E6%8B%B7%E8%B4%9D%E5%92%8C%E6%B5%85%E6%8B%B7%E8%B4%9D/" title="深拷贝和浅拷贝"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
    <li class="toggle-toc">
      <a class="toggle-btn " data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button">    <span>[&nbsp;</span><span>文章目录</span>
        <i class="text-collapsed icon icon-anchor"></i>
        <i class="text-in icon icon-close"></i>
        <span>]</span>
      </a>
    </li>
    
  </ul>
  
  
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-fancy btn-donate pop-onhover bg-gradient-warning" data-toggle="modal" data-target="#donateModal"><span>赏</span></button>
  <!-- <div class="wave-icon wave-icon-danger btn-donate" data-toggle="modal" data-target="#donateModal">
    <div class="wave-circle"><span class="icon"><i class="icon icon-bill"></i></span></div>
  </div> -->
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  
<!-- Modal -->
<div class="modal modal-center modal-small modal-xs-full fade" id="donateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content donate">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <div class="modal-body">
        <div class="donate-box">
          <div class="donate-head">
            <p>感谢您的支持，我会继续努力的!</p>
          </div>
          <div class="tab-content">
            <div role="tabpanel" class="tab-pane fade active in" id="alipay">
              <div class="donate-payimg">
                <img src="/Skyung/images/donate/alipay.jpg" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开支付宝扫一扫，即可进行扫码打赏哦</p>
            </div>
            <div role="tabpanel" class="tab-pane fade" id="wechatpay">
              <div class="donate-payimg">
                <img src="/Skyung/images/donate/wechat.jpg" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开微信扫一扫，即可进行扫码打赏哦</p>
            </div>
          </div>
          <div class="donate-footer">
            <ul class="nav nav-tabs nav-justified" role="tablist">
              <li role="presentation" class="active">
                <a href="#alipay" id="alipay-tab" role="tab" data-toggle="tab" aria-controls="alipay" aria-expanded="true"><i class="icon icon-alipay"></i> 支付宝</a>
              </li>
              <li role="presentation" class="">
                <a href="#wechatpay" role="tab" id="wechatpay-tab" data-toggle="tab" aria-controls="wechatpay" aria-expanded="false"><i class="icon icon-wepay"></i> 微信支付</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>



</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="/Skyung/null" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/Skyung/null" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="/Skyung/null" target="_blank" title="Twitter" data-toggle=tooltip data-placement=top><i class="icon icon-twitter"></i></a></li>
        
        <li><a href="/Skyung/null" target="_blank" title="Behance" data-toggle=tooltip data-placement=top><i class="icon icon-behance"></i></a></li>
        
        <li><a href="/Skyung/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/Skyung/js/plugin.min.js"></script>


<script src="/Skyung/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/Skyung/',
        CONTENT_URL: '/Skyung/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/Skyung/js/insight.js"></script>






   




   
    
    <script defer type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=[object Object]"></script>








</body>
</html>